Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 182 ยท Variables and Types

Integer Types

Learn every C# integer type from sbyte to ulong, nint, Int128 and BigInteger - ranges, literals, overflow, checked and unchecked, and integer division pitfalls.

Whole numbers are the workhorse of programming: counters, indexes, ages, prices in cents, file sizes. C# offers eight fixed-size integer types plus a few special ones, because choosing a size is a trade between range and memory. Most of the time you will use int, but knowing the others, and what happens when a calculation leaves the allowed range, separates safe code from code with silent bugs.

In this lesson you will learn the integer family and its ranges, how to write literals in decimal, hexadecimal and binary, how overflow behaves and how checked catches it, why 7 / 2 is 3, and what to use when long is still too small.

The integer family

Each type has a fixed number of bits. Signed types use one bit for the sign and can be negative; unsigned types start at zero and reach twice as high.

C# keyword .NET type Size Range
sbyte SByte 8 bits -128 to 127
byte Byte 8 bits 0 to 255
short Int16 16 bits -32,768 to 32,767
ushort UInt16 16 bits 0 to 65,535
int Int32 32 bits -2,147,483,648 to 2,147,483,647
uint UInt32 32 bits 0 to 4,294,967,295
long Int64 64 bits about -9.22 x 10^18 to 9.22 x 10^18
ulong UInt64 64 bits 0 to about 1.84 x 10^19

The keyword and the .NET name are the same type: int is just a friendly alias for System.Int32. Every one of them has MinValue and MaxValue constants, so you never have to memorize the numbers.

C# Ranges of the integer types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Which one should you use?

  • int is the default. It is the natural size for most CPUs, the type of array lengths and indexes, Count properties and loop counters, and the type that integer literals get. Use it unless you have a reason not to.
  • long when values may exceed about two billion: file sizes, timestamps in milliseconds, database ids that will grow, factorials.
  • byte for raw binary data (byte[] buffers, network and file formats), not for small numbers. Arithmetic on byte and short is awkward, as you will see below.
  • uint and ulong mostly for bit patterns, hash values and interop. Do not use unsigned types just because "a count cannot be negative"; mixing signed and unsigned values causes surprises, and the standard library uses int for sizes.
  • sbyte, short, ushort: rarely needed, mainly for file formats or big arrays where memory counts.

Literals

A number written in code is a literal. By default it is an int if it fits, otherwise a long, otherwise ulong. Suffixes force the type: L for long, U for uint, UL for ulong.

You can also write numbers in other bases and group digits with underscores, which the compiler ignores:

C# Literals: hex, binary, separators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Hexadecimal (0x) is common for colors, masks and byte values; binary (0b) makes bit flags readable. Use separators to make large numbers legible: 1_000_000 is much easier to check than 1000000. There is no octal literal syntax in C# (a leading zero is just a zero).

Arithmetic and integer division

The usual operators + - * / % work on integers. % is the remainder. The one that surprises newcomers is division: dividing two integers gives an integer and throws away the fraction. It truncates toward zero, it does not round.

C# Integer division and remainder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Dividing an integer by zero throws DivideByZeroException. Dividing a double by zero does not throw; it produces infinity (see Floating-Point and decimal). The % operator is the key to wrapping around (clock arithmetic), checking even/odd (n % 2 == 0) and splitting values like minutes into hours and minutes.

byte and short arithmetic promotes to int

Operations on types smaller than int are performed as int and produce an int. So this innocent code does not compile:

C#
byte a = 100;
byte b = 50;
byte sum = a + b;   // error CS0266: Cannot implicitly convert type 'int' to 'byte'

You must convert the result back explicitly, byte sum = (byte)(a + b);, and that is exactly where overflow can sneak in.

Overflow

Every integer type has a limit. What happens when a result does not fit? By default, C# wraps around silently, like an odometer rolling over, with no exception.

C# Overflow wraps silently by default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The wrong answer 1410065408 is the real result, 10,000,000,000, with its high bits cut off. Notice the fix: (long)a * a converts one operand first, so the multiplication happens in 64 bits. Writing (long)(a * a) would not help, because the overflow has already happened inside the parentheses.

Silent wrap-around has caused real-world disasters (rockets, bank balances, loops that never end). C# lets you choose to be told about it.

checked and unchecked

A checked context turns overflow into an OverflowException. You can apply it to one expression or to a whole block. unchecked does the opposite and is the default for non-constant expressions.

C# checked catches overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You can turn checking on for a whole project with <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> in the .csproj (see The dotnet CLI, Projects and Tooling). The cost is small but real, so most programs leave it off and use checked only where wrong numbers would be dangerous: money, sizes passed to allocation, index calculations from external input. A compile-time constant expression that overflows, such as int x = int.MaxValue + 1;, is rejected with error CS0220: The operation overflows at compile time in checked mode.

Many library methods also offer overflow-safe variants: Math.Abs(int.MinValue) throws OverflowException (the positive value does not exist), and int.CreateChecked(...)/CreateSaturating(...) convert with a chosen policy.

Bits: shifts and masks

Integers are bit patterns, and the bitwise operators & | ^ ~ << >> work on them. This is how flags, hash functions and file formats are handled; see Operators for the full set.

C# Bit operations on integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The static helpers (PopCount, IsPow2, LeadingZeroCount, Log2) come from the generic math interfaces (.NET 7, C# 11) and are typically implemented with single CPU instructions.

Native-sized integers: nint and nuint

nint and nuint are integers whose size matches the process: 32 bits in a 32-bit process, 64 bits in a 64-bit process. They exist for interop with native code and pointer arithmetic, not for everyday use. In ordinary code prefer int and long.

Beyond 64 bits: Int128 and BigInteger

Two types go further. Int128 and UInt128 (.NET 7) are fixed-size 128-bit integers. System.Numerics.BigInteger grows as needed, limited only by memory, and never overflows.

C# Int128 and BigInteger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

30! has 33 digits and does not fit in any built-in fixed-size type, but BigInteger handles it. It is slower and allocates memory, so use it for cryptography, exact large arithmetic and puzzles, not for loop counters. See Math, BigInteger and Random for more.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Console.WriteLine(-7 / 2); print?

    Integer division truncates toward zero, so -7 / 2 is -3.
  2. 2. By default, what happens when int.MaxValue + 1 is computed at run time?

    Unchecked arithmetic wraps silently. Use a checked context to get an OverflowException instead.
  3. 3. Why does byte c = a + b; fail for two bytes a and b?

    Arithmetic on byte and short operands promotes them to int, so the result must be cast explicitly to byte.
  4. 4. Which expression multiplies two int values a and b safely in 64 bits?

    Converting one operand to long first makes the multiplication happen in 64 bits. Casting the finished int product is too late.
  5. 5. Which type has no fixed upper limit on its value?

    BigInteger grows with the value and is bounded only by memory. All other integer types have a fixed bit width.

Summary

  • C# has sbyte, byte, short, ushort, int, uint, long and ulong; use int by default, long for large values, byte for raw data.
  • Literals can be decimal, hexadecimal (0xFF) or binary (0b1010), with _ separators and suffixes L, U, UL.
  • Integer division truncates toward zero and % keeps the dividend's sign; dividing by zero throws DivideByZeroException.
  • Arithmetic on byte and short is done as int, so results need an explicit cast back.
  • Overflow wraps silently by default; checked (an expression, a block or a project setting) throws OverflowException, unchecked allows wrapping explicitly.
  • Convert one operand to the wider type before multiplying to avoid overflow in intermediate results.
  • nint/nuint match the process size for interop; Int128 is fixed 128-bit and BigInteger is unlimited but slower.

Next: Floating-Point and decimal