#22 – Integer Literals

There are several ways to specify integer literals in C#.  The type is inferred from the value specified.  The type used will be the first type in the following list that the literal fits into: int, uint, long or ulong.  A suffix can also be used to help indicate the type of the literal.

Types chosen based on suffix (in order preferred):

  • u suffix – uint, ulong
  • l suffix – long, ulong
  • ul suffix – ulong

Here are a few examples:

// Decimal literals, suffixes
object o1 = 42;           // int
object o2 = 2147483647;   // int
object o3 = 2147483648;   // uint
uint u1 = 2;              // uint
object u2 = 100U;         // uint
object o4 = 4294967296;   // long
object o5 = 4294967296U;  // ulong
object o6 = 42L;          // long
object o7 = 9223372036854775808L;  // ulong
object o8 = 42UL;         // ulong
int n1 = 003;

// Hexadecimal literals
int x1 = 0x1A2;     // 418
object o12 = 0xFFFFFFFF;   // 4294967295 uint
object o13 = 0xFUL;   // 15, ulong

Lowercase suffixes are allowed, but you should use uppercase for clarity.

Advertisements