C# Literal Types

Posted by William on Jan 13, 2010

When you are specifying literal numeric values in your code you will, on occasion, have to give the compiler a heads-up on the expected type from the declaration.

For example, the literal value 5.3 will, by default, be assumed to be a double. As such, the following

1
float result = 5.3 / 12.4;

will result in the exception

Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?)

You could cast the value but that would create an unneccessary overhead and result in messy code.

1
2
3
float result = (float)5.3 / (float)12.4; 
or
float result = (float)(5.3 / 12.4);

The most suitable way to approach this is to advise the compiler on the literal type. You do this by applying a suffix to your literal.

1
float result = 5.3f / 12.4f;

This can also be used when passing a literal as a parameter in a method signature.

1
MyObject.MyMethod(12.5m);

A table of the most common literal type declarations can be seen below.

1
2
3
4
5
6
var x = 1m;  // decimal
var x = 1f;  // float
var x = 1d;  // double
var x = 1l;  // long
var x = 1u;  // uint
var x = 1ul; // ulong