#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #22 – Integer Literals

  1. Pingback: #1,054 – Implicit Conversions from Constant Expressions | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: