Wednesday, April 20, 2011

Why should we use literals in C#?

In some C# code I have seen staments like this:

float someFloat = 57f;

I want to know why we should use literals like f in the above case?.

From stackoverflow
  • Mainly so the compiler knows exactly what we mean - in particular for overload resolution:


    should that call Foo(int) / Foo(float) / Foo(decimal) ?

    Actually, I don't like remembering things - an alternative is:

    float someFloat = (float)57;

    this is not a runtime cast - it is identical (at the IL level) to 57f. The only time it is subtly different is with decimals with extra precision:

    decimal someDecimal = (decimal)57.0; // same as 57M, not 57.0M (scale is different)
  • The "f" above is a type suffix. This tells the compiler the exact type of the literal provided. This is used so the compiler can allocate the appropriate amount of storage (precision) for the literal. By default, floating point literals are given storage for a "double." If you add "f" as a suffix, the literal will only get the storage for a float, which will have less accuracy.

    double d = 50.1234; // given double storage
    double d = 50.1234f; // given float storage, which might lose precision compared to double
  • By default, a real numeric literal on the right-hand side of the assignment operator is treated as double. Therefore, to initialize a float variable use the suffix f or F, for example:

    float x = 3.5F;

    If you don't use the suffix in the previous declaration, you will get a compilation error because you are attempting to store a double value into a float variable.

    From MSDN: float

  • Because 57 is an integer and 57.0 is a double. You're trying to get a float, which is a single precision number. That begs the question, why are you using a single precision float?

    See for some more on C# literals.

  • Check out this article which explains a lot about Numeric Literals in C#:

    Here is a little excerpt from the article:

    float unitPrice = 123.45; // This will not compile

    The problem here is that you cannot always implicitly convert a double (123.45) into a float. The C# compiler understands this and stops the code from being compiled

  • I want to know why we should use literals like f in the above case?.

    You shouldn't. Well, you don't have to.

    The above case shows a float initialization to 57f. Integers are implicitly converted to floats compile time so you can easily strip away that f suffix if that bothers you. However, for consistency in written code, I always try to add the suffix. Note that this only applies to rounded numbers (integers).

    See Msdn on Implicit and Explicit number conversations.


Post a Comment