Tuesday, March 17, 2009

TryParse, TryParseExact for conversion in .net

Today, I discover a userful function called TryParse in .net programming.

Previously, if we want to convert a string to integer, we will:
Convert.ToInt32(sampleString);

However, we need to catch the Exception if the variable cannot be casted into integer. With the use of TryParse(), it will return false if the variable cannot be parsed:
int.TryParse(sampleString);

It saves some work and makes the code nicer. Also, catching exception is consuming. So TryParse() is really a good tool to use.

No comments: