Summary: in this tutorial, you’ll learn how to use the C# integer types to represent the integer numbers.
Introduction to the C# integers #
Integers are whole numbers for example -1, 0, 1, 2, 3. C# uses the integral numeric types to represent integer numbers. So far, you have learned how to use the int type to declare a variable that holds an integer.
Besides the int type, C# has other integer types with their specific keyword, range, and size.
The following table illustrates the characteristics of all the integer types in C#:
| C# type/keyword | Range | Size |
|---|---|---|
sbyte | -128 to 127 | Signed 8-bit integer |
byte | 0 to 255 | Unsigned 8-bit integer |
short | -32,768 to 32,767 | Signed 16-bit integer |
ushort | 0 to 65,535 | Unsigned 16-bit integer |
int | -2,147,483,648 to 2,147,483,647 | Signed 32-bit integer |
uint | 0 to 4,294,967,295 | Unsigned 32-bit integer |
long | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Signed 64-bit integer |
ulong | 0 to 18,446,744,073,709,551,615 | Unsigned 64-bit integer |
C# also has other two integer types nint and nunit whose ranges depend on the specific platform.
If you declare a variable with an integer type and assign a value that is out of range, you’ll get a compilation error.
For example, the following declares a variable age with the type byte and initializes its value to an invalid value 256:
byte age = 256;When you compile the code, the compiler issues the following error:
error CS0031: Constant value '256' cannot be converted to a 'byte'Min and max values #
Each integer type has the MinValue and MaxValue constants that provide the minimum and maximum of the type. To access these values, you use the dot operator (.). For example:
int.MinValue
int.MaxValueThe following displays the range of the int type:
Console.WriteLine($"int range: ({int.MinValue},{int.MaxValue})");Output:
int range: (-2147483648,2147483647)Integer literals #
Integer literals can be decimal, hexadecimal, and binary.
Decimal #
The following example shows the integer literals in decimal without any prefix:
int quantity = 10;
int amount = 20;If a number is big, you can use the digit separator (_) to make it more readable. Note that you can use the digit separator (_) for all integer literals, not just decimal. For example:
int prize = 1_000_000;Hexadecimal #
Hexadecimal numbers have the 0x or 0X prefix. For example:
int address = 0x5A;Binary #
Binary numbers have the 0b or 0B prefix. For example:
int flag = 0b10011110;Also, you can use the digit separator (_) to separate the digits like this:
int flag = 0b_1001_1110;Summary #
- Use C# integer type to represent integer numbers.
- Use digit separator (
_) with big numbers to make them more readable.
Thank you for your feedback!