Convert double to float by cast or Convert.ToSingle()?

In C# I can convert doubles to floats by a cast (float) or by Convert.ToSingle().

double x = 3.141592653589793238463;
float a = (float)x;
float b = Convert.ToSingle(x);

a and b become equal.

Are there any differences between both techniques? Which one should I prefer and why?

135358 次浏览

From the .NET reference source:

public static float ToSingle(double value)
{
return (float)value;
}

So, your answer is that they are exactly the same, under the hood.

Any preference between the two is strictly a personal style choice. Personally, I would always use the cast as it is shorter and and just seems more idiomatic to me.

While they are exactly the same when casting a double, there is a difference if the double has been cast to an object.

object x = 1.0;
float a = (float)x;              //InvalidCastException
float b = Convert.ToSingle(x);   //OK

The .NET reference source for how it is done is a few lines above the answer provided by @Glorin.