Have you ever considered between the methods which are used convert to integer? If yes or no, please continue to read. When you write code, probably you use convert process between types. Especially from string type to integer type. NET Framework 1.x supports two methods for converting. One of them is Int32.Parse and another is Convert.ToInt32. And also in .NET framework 2.0, Int32.TryParse is available in c#. Ok let's begin to explain what are differences between them.First of all. we define the variables to be used following examples.
string s1 = "123";
string s2 = "123.45";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";
int result;
bool success;
Int32.Parse(string s)
When s is null, ArgumentNullException is throwed, if s is not integer value, FormatException is throwed. If s represents number less than MinValue or grater than MaxValue, OverFlowExceptin is throwed.
result = Int32.Parse(s1); //output --> 123
result = Int32.Parse(s2); //output --> FormatException
result = Int32.Parse(s3); //output --> ArgumentNullException
result = Int32.Parse(s4); //output --> OverflowException
Convert.ToInt32(string s)
When s is null, zero is returned, if s is not integer value, FormatException is throwed. If s represents number less than MinValue or grater than MaxValue, OverFlowExceptin is throwed.
result = Convert.ToInt32(s1); //output --> 123
result = Convert.ToInt32(s2); //output --> FormatException
result = Convert.ToInt32(s3); //output --> 0
result = Convert.ToInt32(s4); //output --> OverflowException
Int32.TryParse(string, out int)
When s is null or not integer value, zero is returned.
success = Int32.TryParse(s1, out result); //output --> true; result => 123
success = Int32.TryParse(s2, out result); //output --> false; result => 0
success = Int32.TryParse(s3, out result); //output --> false; result => 0
success = Int32.TryParse(s4, out result); //output --> false; result => 0
As a result, Int32.TryParse is most usefull and better. it reduces the risk of converting to integer during runtime.