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

C#.NetCastingType Conversion

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSebView Question on Stackoverflow
Solution 1 - C#Glorin OakenfootView Answer on Stackoverflow