Question

I noticed in another post, someone had done something like:

double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));

Why did they use the convert function, rather than:

double d = 3.1415;
int i = (int)d;

which has an implicit floor and convert.

Also, more concerning, I noticed in some production code I was reading:

double d = 3.1415;
float f = Convert.ToSingle(d);

Is that the same as:

float f = (float)d;

Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.

Was it helpful?

Solution

Casting to int is implicit truncation, not implicit flooring:

double d = -3.14;
int i = (int)d;
// i == -3

I choose Math.Floor or Math.Round to make my intentions more explicit.

OTHER TIPS

Rounding is also handled differently:

x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2
x=-1.5 (int)x=-1 Convert.ToInt32(x)=-2
x=-0.5 (int)x= 0 Convert.ToInt32(x)= 0
x= 0.5 (int)x= 0 Convert.ToInt32(x)= 0
x= 1.5 (int)x= 1 Convert.ToInt32(x)= 2
x= 2.5 (int)x= 2 Convert.ToInt32(x)= 2

Notice the x=-1.5 and x=1.5 cases.
In some algorithms, the rounding method used is critical to getting the right answer.

You can use Convert when you have a string that you want to convert to an int

int i = Convert.ToInt32("1234");

Convert and casting will both throw an exception if they fail.

i.e, this will still throw an exception, it will not return 0:

Convert.ToInt32("1234NonNumber");

In many cases Convert and casting will have the same result, but a cast is often times easier to read.

Convert.ToInt32() is used on strings (http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) while casting can only be used on types that have internal converters (numeric types). The real trick comes in deciding between Int32.Parse and Convert.ToInt32(). Convert.ToInt32() is tolerant of a null parameter and returns 0 while Int32.Parse() will throw an ArgumentNullException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top