TryParse() method in .NET 2.0

TryParse method is exposed by several classes in the System namespace

System.Boolean.TryParse(System.String,System.Boolean)
System.Byte.TryParse
System.DateTime.TryParse
System.Char.TryParse(System.String,System.Char)
System.Decimal.TryParse
System.Double.TryParse
System.Int16.TryParse
System.Int32.TryParse
System.Int64.TryParse
System.SByte.TryParse
System.Single.TryParse
System.UInt16.TryParse
System.UInt32.TryParse
System.UInt64.TryParse

TryParse isA0 new in .NET 2.0 which provide the functionality to check if the type applicable to be parsed or not without raising an exception like Parse method do, and this of course solved and replaced the common snippet written by each developer to ensure proper handling for type parsing.

.NET 1.1A0A0

 1: try
 2: {
 3:  int.Parse(sampleString);
 4:  }
 5: catch(System.FormatException formatException)
 6: {
 7:  Console.WriteLine("invalid string formate");
 8: }

In .NET 2.0 you can use the following

 1:  if (int.TryParse(sampleString, out number))
 2:  Console.WriteLine(number);

What about Performance !!!

For Performance comparison between both methods you can read IanWho's post about this here Performance Profiling Parse vs. TryParse vs. ConvertTo

No Comments