string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";
result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException
result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException
success = Int32.TryParse(s1, out result); //-- success => true; result => 1234
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0
Why do we need these many conversion functions when the intent of the operation is to just convert a string to int.
I am sorry if my question is stupid.
They do 3 different things:
Int32.Parse()expects a string which is an exact representation of an integer. It is extremely limited – it either parses a string or explodes.Int32.TryParse()is the same as Parse, but has the extra overhead of performing validation. So in cases where you aren’t sure if the incoming string is parseable, it’s better thanParseand catching an exception (very expensive). ButTryParseis wasteful in cases where you can be highly confident a simpleParsewill do.Convert.ToInt32is the most complex – it actually determines if the incoming object is convertible, not parseable, to an int. It supports converting between many native (known) types, but also inspects the incoming object to see if the object provides its own logic viaIConvertibleessentially saying “yes, I can be converted to an integer – here’s how”.