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?
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.