C# Numeric Suffix Examples

Understand the usage of suffixes on literals. See examples of numeric suffix syntax.
Suffixes specify number types. They instruct the C# compiler that an integral literal such as 1000 be considered a certain type of number—for example, a long (1000L). We look into how you can add numeric suffixes to numbers.Long
First example. Numeric suffixes, which are also called literal number suffixes, are hints to the compiler that a literal number is of a certain type. Recall that "literal" means a value hard-coded into your program.

Note: Literal suffixes on constants actually generate conv instructions. This means they work the same as runtime casts.

Letters: The letters L, D, F, U, M and UL are appended to the end of the integral literals in the declarations.

And: An "L" instructors the C# compiler that 10000 is a long type. The MSIL generated is similar to using casts such as (long)10000.

IL Disassembler
C# program that uses literal number suffixes using System; class Program { static void Main() { // Use long suffix. long l1 = 10000L; // Use double suffix. double d1 = 123.764D; // Use float suffix. float f1 = 100.50F; // Use unsigned suffix. uint u1 = 1000U; // Use decimal suffix. decimal m2 = 4000.1234M; // Use unsigned suffix and long suffix. ulong u2 = 10002000300040005000UL; } }
Review. We describe the suffixes in more detail. This table indicates the meaning of the letters. We also see examples of the suffixes in the C# programming language. The code statements can be used within programs.
Syntax table Suffix type: unsigned int Character: U Example: uint x = 100U; Suffix type: long Character: L Example: long x = 100L; Suffix type: unsigned long Character: UL Example: ulong x = 100UL; Suffix type: float Character: F Example: float x = 100F; Suffix type: double Character: D Example: double x = 100D; Suffix type: decimal Character: M Example: decimal x = 100M;
Lowercase suffixes. You can also specify lowercase suffixes, such as u, l, ul, f, d and m. But these are easier to confuse with numbers. The letter "l" is sometimes seen as the number 1.

Warning: The "l" suffix is easily confused with the digit 1—use L for clarity. The screenshot shows this warning in the IDE.

Examples of lowercase suffixes Lowercase suffix: long x = 10000l; // Is that 100001 or 10000l? Uppercase suffix: long x = 10000L; // It's 10000L.
Summary. Suffixes can be used on literal numbers in C# programs. This is a way to tell the C# compiler that you want the literal number to be treated as a certain type of number, similar conceptually to a cast.

Note: The specification defines how numbers are converted when used as operands, but these suffixes can force certain conversions.

Numeric Casts
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls