Search code examples
c#floating-pointliteralssuffix

Is there a reason to always declare floats with the type suffix 'f' in C#?


When creating float variables, integers don't need a type suffix, i.e. all of these are valid:

public float distance = 3;
public float distance = 3f;
public float distance = 0.3f;

Is there a reason to use 3f instead of 3? Is the compiler smart enough to recognize the type as float and automatically cast it?

Related Questions: Why Should we use literals in C# and Why is the "f" required when declaring floats

Both explain why we need to use the type suffix 'f', but is there a 'correct' way to declare floats that have integer values? Is one way more efficient?


Solution

  • Here is the list of allowed Implicit Numeric Conversions. Implicit conversions are allowed when the target type can hold the original type range. In the case, float distance = 0.3; is an error because a float range cannot accommodate the double range.

    As to efficiency, between 3 and 3f, the compiler should optimize for you.

    IL_0001:  ldc.r4     3.   // float distance1 = 3;
    IL_0006:  stloc.0
    IL_0007:  ldc.r4     3.   // float distance2 = 3f;
    IL_000c:  stloc.1