Tuesday, July 1, 2014

In C#, you should see if a string may be cast to an int with TryParse instead of a try/catch.

This test will pass:

[TestMethod]
public void TestStringToIntegerCasting()
{
   int result = 0;
   string ate = "ate";
   bool judgement = int.TryParse(ate, out result);
   Assert.AreEqual(judgement, false);
   Assert.AreEqual(result, 0);
   
   string eight = "8";
   judgement = int.TryParse(eight, out result);
   Assert.AreEqual(judgement, true);
   Assert.AreEqual(result, 8);
}

 
 

.TryParse may be used with several other types too such as DateTime. There is going to be way to check to see if you may cast whenever you need to cast in lieu of just relying on a try/catch to figure it out. I used to do the try/catch thing because I didn't know any better. Now I know better. This touches on .IsAssignableFrom some.

No comments:

Post a Comment