C# Integers

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/keywordRangeSize
sbyte-128 to 127Signed 8-bit integer
byte0 to 255Unsigned 8-bit integer
short-32,768 to 32,767Signed 16-bit integer
ushort0 to 65,535Unsigned 16-bit integer
int-2,147,483,648 to 2,147,483,647Signed 32-bit integer
uint0 to 4,294,967,295Unsigned 32-bit integer
long-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807Signed 64-bit integer
ulong0 to 18,446,744,073,709,551,615Unsigned 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;Code language: C# (cs)

When you compile the code, the compiler issues the following error:

error CS0031: Constant value '256' cannot be converted to a 'byte'Code language: plaintext (plaintext)

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.MaxValueCode language: CSS (css)

The following displays the range of the int type:

Console.WriteLine($"int range: ({int.MinValue},{int.MaxValue})");Code language: C# (cs)

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;Code language: C# (cs)

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;Code language: C# (cs)

Hexadecimal

Hexadecimal numbers have the 0x or 0X prefix. For example:

int address = 0x5A;Code language: C# (cs)

Binary

Binary numbers have the 0b or 0B prefix. For example:

int flag = 0b10011110;Code language: C# (cs)

Also, you can use the digit separator (_) to separate the digits like this:

int flag = 0b_1001_1110;Code language: C# (cs)

Summary

  • Use C# integer type to represent integer numbers.
  • Use digit separator (_) with big numbers to make them more readable.
Was this tutorial helpful ?