C# suffix behind numeric literal

You are confusing two different things here:

float testFloat = 3.0F;

The float tells the compiler that the variable testFloat will be a floating point value. The F tells the compiler that the literal 3.0 is a float. The compiler needs to know both pieces before it can decide whether or not it can assign the literal to the variable with either no conversion or an implicit conversion.

For example, you can do this:

float testFloat = 3;

And that's okay. Because the compiler will see 3 as a literal integer, but it knows it can assign that to a float without loss of precision (this is implicit conversion). But if you do this:

float testFloat = 3.0;

3.0 is a literal double (because that's the default without a suffix) and it can't implicitly (i.e. automatically) convert a double to a float because a float has less precision. In other words, information might be lost. So you either tell the compiler that it's a literal float:

float testFloat = 3.0f;

Or you tell it you are okay with any loss of precision by using an explicit cast:

float testFloat = (float)3.0;

All1 expressions need to be resolvable to a type. So the expression 42 always needs to have exactly one type (it happens to be an int). It can't be an int if you assign it to an int variable and a double if you assign it to a double. The context that an expression is used in is never1 used to determine what type it resolves to.

This is why numeric literals can have suffixes; it's a way of defining the type of that expression in that expression.

Note that there are also implicit conversions between many of the numeric types, so if you write double d = 42; the expression 42 is actually an integer, but there is an implicit conversion operator being performed on it that will convert it into a double before the assignment.

1 There are a few exceptions here, such as lambdas, to which the type of the expression is dependent on how its used, and method groups; in a vacuum these expressions have no type.


Exists other way to declare a variable without specify the type before the name:

var myNumber = 10;

In this case, the variable type will be defined by the literal value.

If you use the type (double|float|int|...) instead "var", the compiler make a conversion of literal value to variable type (when is possible).

So, I think that suffix is important when you use "var" to declare variables and the literal value type is not the default associated when the suffix is not used;

There is another reason when use suffix is too useful, like in situation that you want make implicit conversions in expressions.