What is the difference between int.Parse() and int.TryParse() ? Or how the int.parse() is differ from int.TryParse() ? – yet another frequently asked question in interview for the beginners, and I have seen confusion while answering this. Let’s try to understand using simple example. To answer this in a sort way, the int.Parse() and int.TryPrase() methods is used to convert a string representation of number to an integer. In case of the string can’t be converted the int.Parse() throws an exceptions where as int.TryParse() return a bool value, false.
Let’s try to understand with a simple example as shown in below.
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.
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.
Hope this will give you a clear picture now. Let’s put them in side by side !
Which one is best ? In my opinion, int.TryParse() will be the better way as it handles the exceptions by it’s own and you can just focus on the values. Again, this will totally depends in which context you want to use it. if you want to know when it is failing and why it is then you should go for int.parse.
Well, this is not the end, to make the discussion more interesting you may asked another question during this overall discussion. So how they differ with Convert.ToInt32() ? I will leave this up to you now to explore this …
Hope this helps !!