a blog for those who code

Friday 27 June 2014

Difference Between Convert.ToInt32(), Int32.Parse() and Int32.TryParse()

The difference between Convert.ToInt32(), Int32.Parse() and Int32.TryParse() are as follows...

Convert.ToInt32(string)

Convert.ToInt32(string) method converts the string to 32-bit integer. This method will return 0 if the string is null, but it will throw FormatException if string is other than integer. If string represents a number which is not in the 32-bit integer range it will throw OverflowException.

Int32.Parse(string)

Int32.Parse(string) method converts the string to 32-bit integer. If string is null it will throw ArgumentNullException. It will throw FormatException if string is other than integer. If string represents a number which is not in the 32-bit integer range it will throw OverflowException.

Int32.TryParse(string, out int)

Int32.TryParse(string, out int) method converts the string to 32-bit integer which is stored in int variable. It returns true if its able to convert the string to integer otherwise it will return false. When string is null int variable will be 0 and when string is not an integer or its value is not in the range the integer value will be 0.

So, better try to use Int32.TryParse(string, out int) to avoid exceptions. But, sometimes exception are good as you will be able to know that what you are doing wrong.

Please like and share the blog if you find it interesting and helpful.

No comments:

Post a Comment