C# Reference ยท Types and Literals
Integer types: int, long, short, byte
Reference for C# integer types: sbyte, byte, short, ushort, int, uint, long, ulong, nint and nuint, their ranges, literals, overflow, division and conversions.
C# has a family of integral types with different sizes and signs. int (32-bit signed) is the default choice for counting and indexing. long (64-bit) is for large values such as file sizes and timestamps. byte, short and the unsigned variants exist for compact storage and binary data.
All of them are structs in the System namespace (int is System.Int32), and all have MinValue and MaxValue constants and parsing methods.
int count = 42; long big = 3_000_000_000L; byte flag = 0b0000_0101;
Try it
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.
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.
Syntax
| 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 |
nint, nuint |
IntPtr, UIntPtr |
pointer size | platform dependent |
Literals: decimal 42, hexadecimal 0x2A, binary 0b101010, with _ as separator. Suffixes: L (long), U (uint), UL (ulong). A literal with no suffix is the first of int, uint, long, ulong that fits.
Errors: OverflowException in checked code; DivideByZeroException for integer / or % by zero; FormatException or OverflowException from Parse.
Usage notes
- Integer division truncates toward zero, and
%takes the sign of the left operand. - Arithmetic on
byte,sbyte,shortandushortis done inint, so the result ofx + yis anintand needs a cast to store in abyte. - Overflow wraps silently by default. Use
checkedwhen wrong results are worse than an exception. int.MinValue / -1andMath.Abs(int.MinValue)throwOverflowException.- Mixing signed and unsigned types in expressions is error-prone. Prefer
intfor indexes and sizes; the framework usesintforLengthandCount. - Use
TryParsefor user input.Parsethrows on bad input. - Since .NET 7 every integer type implements generic math interfaces such as
INumber<T>, soint.Max,int.Clampandint.CreateCheckedexist. Int128andUInt128provide 128-bit integers;System.Numerics.BigIntegeris unbounded.- Convert between types with casts.
Convert.ToInt32(double)rounds to even; a cast(int)2.9truncates.