Difference Between int.Parse() and int.TryParse()

What is the difference between int.Parse() and int.TryParse()? Or how is int.parse() different from int.TryParse()? – another common interview question for freshers and I noticed some confusion when answering it.

Let’s try to understand using a simple example. To answer this question in a sorted way, the int.Parse() and int.TryPrase() methods are used to convert the string representation of a number to an integer. In case the string cannot be converted, int.Parse() returns an exception while int.TryParse() returns a Boolean value, false.

int.Parse()

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

Difference Between int.Parse() and int.TryParse()

In this case, the val string will be converted to an integer without any error or exception; and this is the purpose of the int.Parse() method. The int.Prase() method throws three different types of exceptions depending 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.
Difference Between int.Parse() and int.TryParse()

int.TryParse()

In case of int.TryParse() method, when it converts string representation of a number to integer; it sets variable with integer result and returns true if parsing is successful, otherwise false.

Difference Between int.Parse() and int.TryParse()

Keep in mind the int.TryParse() case, in case there is no exception. It’s a null parameter, incorrect format, or a null integer. Each time the result value will be set to 0 and the method will return false.

Difference Between int.Parse() and int.TryParse()
Difference Between int.Parse() and int.TryParse()

I hope this has given you a clear picture now. Let’s put them next to each other!

Difference Between int.Parse() and int.TryParse()

Which one is best? In my opinion int.TryParse() would be the best way as it handles exceptions itself and you can focus only on the values. Again, it depends entirely on the context in which you want to use it. If you want to know when it fails and why, you should go to int.parse.

Well,how above are different from Convert.ToInt32()? I’ll let you explore this now and you can also update using your commnets.

You can check more article on our website HERE under C# section or you can also check same on Micrsoft Docs too.

Leave a Reply

Your email address will not be published. Required fields are marked *