Difference between Convert.ToInt32 and Int.Parse method
Posted on 5/16/2007 9:59:16 AM
in #ASP.NET 2.X
Hi
Today one of my colleagues came up with an interesting question in the office. If we want to convert a string value (Lets say we have a string “23”) to integer we have 2 options. One is to use the Int.Parse method and other is to use the Convert.ToInt32.
The real query with every one was what is the difference between the two. The answer is null handling. The difference between the 2 is the manner in which null is handled. If you pass a null value to convert.ToInt32 method it will return back 0. But the same is not true with Int.Parse. If we pass null to Int.Parse method it will throw an ArgumentNullException exception.
Although Convert.ToInt32 method does not throw an exception but it can have a big drawbacks. If you use it on a query string value(where u are also expecting the value 0) then the Convert.ToInt32 might cause programmatic error.
Thanks Vikram
|
Posted on 5/17/2007 12:17:40 PM
In Framework 2.0, there is another way to convert a string to integer which is Int.TryParse(string, out int):bool. Using the new static method can avoid the exception and ambiguous result when the string is null.
int outValue;
bool rtnValue = int.TryParse( null, out outValue ); //rtnValue will be false
|