Understanding what the difference is between Convert.ToInt32 and Int32.Parse

One thing I have come to look upon in a critical way is when a fellow developer tells you something and expects you to just take his word for it. Its like a developer saying “I would do it this way” but not give a reason why, or even asking another developer why he does not do it the same way. I have found this situation yesterday and decided to make sure I knew the difference, and specifically it applies to Convert.ToInt32() and Int32.Parse(). What is the difference? Well simply put Convert.ToInt32() will not throw a FormatException if the value you pass is null or not, whereas Int32.Parse will. It means that for Int32.Parse you have to use some try catch logic. With Convert.ToInt32 you do not have to do this.

On this topic I read here and here that you could also use Int32.TryParse, which will try to convert the value to an integer and return true if it succeeds and false if it fails. It uses an out variable to return the result of the conversion. You can check it out on MSDN here.

  • Share/Bookmark

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes