Thursday, July 16, 2020

C# int.Parse() vs int.TryParse()


image

image



















Let’s try to understand with a simple example as shown in below.

image

In this case the string val, would be converted into integer without any error or exception; and that is what is intended with int.Parse() method.

The int.Prase() method throws three different types of exceptions depends on the data provided.

  • If parameter value is null, then it will throw ArgumentNullException
  • If parameter value is other than integer value or not in proper format, it will throw FormatException.
  • if parameter value is out of integer ranges, then it will throw  OverflowException.

 

Incase of  int.TryParse() method, when it converts the string representation of an number to an integer;  it set the the out variable with the result integer and returns true if successfully parsed, otherwise false.

image

Keep in mind in case of int.TryParse(), in case there won’t be any exception. Either it is for null parameter, incorrect format or out of value integer. Everytime, the result value would be set to 0 and method would return false.

 

image

 

No comments :