Difference between Convert.ToInt32, Int32.Parse and Int32.TryParse

This resource explains the difference between Convert.ToInt32, Int32.Parse and Int32.TryParse, and when to use each of them. From this you will get a clear information on the difference between these three methods and when to use each of them.

Learn the difference between Convert.ToInt32, Int32.Parse and Int32.TryParse

When to choose each of them?
Would you like to know the difference between Convert.ToInt32, Int32.Parse and Int32.TryParse? There are actually no explicit scenarios as when to choose each of them. In fact, as you already know, you can choose the TryParse method if you need a safe conversion, i.e., No exceptions being thrown. But otherwise if you know the string value is just a number i.e., string str = "1?, then you can use any of 3 conversion methods. Although such scenarios are rare to occur in real world problems. So the standard guidelines always suggest to use Tryparse method.

Why are there three ways?
Based on different requirements, Microsoft created these 3 APIs for us to use. One of the requirement as already said above is safe conversion without needing to use Try-Catch-Finally at client side. And as per the name sake, Convert class is like a helper class which supports conversion for different types i.e., Int, char, bool, double, etc. Where as Int structure is specific to Int only and it can't be a helper type here. If in case your code is only dealing with string to integer conversions, then you don't have to use Convert helper class, because at this point it's a waste of memory for this static class, but this design is very much hypothetical.

Are there any differences between them?
There are few difference between them in their working actually. Looking at the IL for each of these APIs, I came to know few interesting things:

  • Convert.Int32() first checks input value for null, if it is null then it returns 0.

  • Convert.Int32() internally calls Int32.Parse() method.

  • Int32.Parse() internally calls Number.ParseInt32() method.

  • Int32.Parse() does not check for null, since it directly calls Number.ParseInt32(), this method checks internally for null and throws ArgumentNullException.

  • Int32.TryParse() also does not directly check for null input, but instead it calls Number.TryParse() API which internally checks for null input and returns false if it is.

Hope this helps.

Application Engineer,
Steadfast Technologies


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: