To understand the difference between Convert.ToInt32,int.Parse and (int)
,consider these examples
Convert.ToInt32 has the maximum flexibility in casting a value of a given type to
an integer 1)
long k= 80000;
//Ok :
Console.WriteLine(Convert.ToInt32(k));
//compile time error :int.Parse expects a string data type
Console.WriteLine(int.Parse(k));
//Ok:
Console.WriteLine((int)k);
2)
double b = 200.44;
//Ok
Console.WriteLine(Convert.ToInt32(b));
//int.Parse works with casting string to integer
//only
//This line will generate a compile time error
Console.WriteLine(int.Parse(345.55));
//Ok
Console.WriteLine((int)b);
3)
string c = "100";
//Ok
Console.WriteLine(Convert.ToInt32(c));
//Ok
Console.WriteLine(int.Parse(c));
//Compile time error
//(int) does not work with casting string to integer
//Error statement
Console.WriteLine((int)c);
4) string h=null;
Console.WriteLine(Convert.ToInt32(h));
//It gives 0
//run time error(value cannot be null)
//an exception will be thrown
Console.WriteLine(int.Parse(h));
//Compile time error
Console.WriteLine((int)h);