C#/Diff Between Cast and Convert
Expert: Srini Nagarajan - 11/24/2005
QuestionHello,
int i1 = 5;
double d1 = i1 + 0.99;
int i2 = (int)d1; //result is 5
i2 = Convert.ToInt32(d1);//result is 6
Am confused why does cast and convert in above example have diffrent results.
Thanks and Regards
Anurag
AnswerThe Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse. So the only difference is that if a null string is passed to Convert it returns 0, whereas Int32.Parse throws an ArgumentNullException.
It is really a matter of choice whichever you use.
Also have a look at the new .NET 2.0 method Int32.TryParse, which attempts to convert a string to an int without throwing an exception.
CHeck this URL given more info
http://blogs.msdn.com/csharpfaq/archive/2004/05/30/144652.aspx
Happy Programming!!
-Srini