Convert double to float by cast or Convert.ToSingle()?
110,763
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.
Comments
-
Seb almost 2 years
In C# I can convert doubles to floats by a cast
(float)
or byConvert.ToSingle()
.double x = 3.141592653589793238463; float a = (float)x; float b = Convert.ToSingle(x);
a
andb
become equal.Are there any differences between both techniques? Which one should I prefer and why?
-
usr over 8 yearsSince there does not seem to be any reason at all to use ToSingle it's not personal choice but objectively better to use a cast.
-
Crusha K. Rool almost 7 yearsThe
Convert
class is meant to be the language-neutral way of converting between the different base types of the .NET Framework. Not all languages that run on .NET actually have a cast operator like C#. For example: in VB.NET you have have CType(), CDbl(), DirectCast() and implicit conversion, none of which have the exact same semantics as the cast operator in C#.