How do I tell C# what kind of literal number I want?

How do I tell C# what kind of literal number I want?

  • Comments 5

If you need to tell C# that you want it to treat a literal as a particular type of number, you may do so by adding a number type suffix at the end of the literal you provide. For example:

1u; // An unsigned int
1l; // A signed long
1ul; // An unsigned long
1f; // A System.Single floating-point number;
1d; // A System.Double floating-point number
1m; // a System.Decimal floating-point number

This is somewhat important because sometimes you must match a literal to the signature of something or specify the value to 'defeat' an implicit cast behavior you don't like. For example, Hashtable names = new Hashtable(100, 0.1); won't compile because the constructor takes parameters (int, float) and the above is (int, double). The line should read Hashtable names = new Hashtable(100, 0.1f);

A full listing of the suffixes is in the Grammar portion of the C# specification (appendix A in the ECMA specification, appendix C in the MS specification). The suffixes are also detailed in the Literals section of the specification (9.4.4 of the ECMA specification, 2.4.4 of the MS specification).

[Author: Jon Skeet]

Leave a Comment
  • Please add 6 and 5 and type the answer here:
  • Post