Friday, September 16, 2011

Difference between Int32.Parse and Convert.ToInt32

Both function use for string format to integer value.

There are some cases

1) If string is null Parse throws ArugmentNullException
2) If String it not compatible to int it throws Format Exception
3) If value is less than Minimum value or greater than Maximum value it will throws Overflow Exception

While in case of Contvert.ToInt32. This function is a wrapper of Int32.Parse. It throws the same exception except in case of null string it returns zero(0).

Example
string s1 = "20";
string s2 = "25.50";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


result = Convert.ToInt32(s1); //-- 25
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException

Int32.TryParse doesn't throws any exception instead it returns zero if value is not compatible. and return false.

success = Int32.TryParse(s1, out result); //-- success => true; result => 25
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

No comments:

Followers

Link