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.

Share:
110,763
Seb
Author by

Seb

Engineering Student

Updated on July 05, 2022

Comments

  • Seb
    Seb almost 2 years

    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?

  • usr
    usr over 8 years
    Since 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
    Crusha K. Rool almost 7 years
    The 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#.