Difference between int.Parse and Convert.ToInt32

15. November 2007 20:16 by Eric in .net  //   Comments (0)

Have been working as a software developer for quite a while, but never thought about what's the different between int.Parse and Convert.ToInt32 from the type conversion perspective.

In the recent project, I couldn't help noticing some quite interesting difference and quickly put down the following code block to demonstrate it:

string convertToInt = "12";
string nullString = null;
string maxValue = "32222222222222222222222222222222222";
string formatException = "12.32";
int parseResult;
// It will perfectly convert interger
parseResult= int.Parse(convertToInt);
// It will raise Argument Null Exception
parseResult= int.Parse(nullString); 
//It willl raise Over Flow Exception 
parseResult= int.Parse(maxValue);
//It will raise Format Exception
parseResult= int.Parse(formatException);
//For Convert.ToInt32
//It will perfectly convert integer
parseResult= Convert.ToInt32(convertToInt);
//It will ouput as 0 if Null string is there
parseResult= Convert.ToInt32(nullString);
//It will raise Over Flow Exception
parseResult= Convert.ToInt32(maxValue);
//It will raise Format Exception
parseResult= Convert.ToInt32(formatException);