Thursday, March 5, 2009

How to validate integer in c#

In C#, we often need to validate that the value is an int. So most developers use try catch block as below.
try
{
int t = Convert.ToInt32("wrongval");
}
catch
{
}

while the best approach to test must be:

int num = 0;
Int32.TryParse("wrongval", out num); //It will not throw any exception, In case of failure, it set the value of num to zero and also return FALSE.


if you see the performance of above two methods, you will be amazed that the TryParse method is 1000 times faster than Convert.ToInt32.

2 comments:

Awais said...

The TryParse method does not throw an exception if the conversion fails.

adeel said...

sorry i have seen your comment today. i have changed it accordingly.
Thanks