You are here:

C#/Diff Between Cast and Convert

Advertisement


Question
Hello,

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

Answer
The 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

C#

All Answers


Answers by Expert:


Ask Experts

Volunteer


Srini Nagarajan

Expertise

can answer any kind of questions in ASP.NET, C#, VB.NET, ASP, SharePoint 2007, Coldfusion, Powerbuilder 7.00 / 8.00, JAVA servlets, MS SQL 2000 / MSSQL7, Sybase

Experience

Contact me if you need any custom development on ASP.NET, ASP, Coldfusion, Powerbuilder

©2012 About.com, a part of The New York Times Company. All rights reserved.