Tuesday 4 December 2012

Difference between Parse and TryParse C#/VB.NET

Difference between Parse and TryParse C#/VB.NET

Step1)  Parse  if string conversion not possible, it throws an exception like FormatException
for ex:
 try
{
DateTime dt2=DateTime.Parse(@"12-03-2012");
Console.WriteLine(dt2.ToString());
}
catch(FormatException ex)
{
}
Step2) TryParse doesn't through any exception simply returns bool value. parsing success true otherwise false.

same thing can be written with TryParse like this


DateTime result;
bool Ret=DateTime.TryParse("12-03-2012", out result);
if(Ret)

   use datetime object result  otherwise not.

                Console.WriteLine(result.ToString());

Same thing applies to Int,Single,Double also.
Int32.Parse,Int32.TryParse.
Single.Parse,Single.TryParse,
Double.Parse,Double.TryParse
methods


No comments:

Post a Comment