int (C# Reference)
int denotes an integral type that stores values according to the size and range shown in the following table.
||-2,147,483,648 to 2,147,483,647||Signed 32-bit integer||System.Int32|
You can declare and initialize an
int variable by assigning a decimal literal, a hexadecimal literal, or (starting with C# 7.0) a binary literal to it. If the integer literal is outside the range of
int (that is, if it is less than Int32.MinValue or greater than Int32.MaxValue), a compilation error occurs.
In the following example, integers equal to 90,946 that are represented as decimal, hexadecimal, and binary literals are assigned to
int intValue1 = 90946; Console.WriteLine(intValue1); int intValue2 = 0x16342; Console.WriteLine(intValue2); int intValue3 = 0b0001_0110_0011_0100_0010; Console.WriteLine(intValue3); // The example displays the following output: // 90946 // 90946 // 90946
You use the prefix
0X to denote a hexadecimal literal and the prefix
0B to denote a binary literal. Decimal literals have no prefix.
Starting with C# 7.0, a couple of features have been added to enhance readability.
- C# 7.0 allows the usage of the underscore character,
_, as a digit separator.
- C# 7.2 allows
_to be used as a digit separator for a binary or hexadecimal literal, after the prefix. A decimal literal isn't permitted to have a leading underscore.
Some examples are shown below.
int intValue1 = 90_946; Console.WriteLine(intValue1); int intValue2 = 0x0001_6342; Console.WriteLine(intValue2); int intValue3 = 0b0001_0110_0011_0100_0010; Console.WriteLine(intValue3); int intValue4 = 0x_0001_6342; // C# 7.2 onwards Console.WriteLine(intValue4); int intValue5 = 0b_0001_0110_0011_0100_0010; // C# 7.2 onwards Console.WriteLine(intValue5); // The example displays the following output: // 90946 // 90946 // 90946 // 90946 // 90946
Integer literals can also include a suffix that denotes the type, although there is no suffix that denotes the
int type. If an integer literal has no suffix, its type is the first of the following types in which its value can be represented:
In these examples, the literal 90946 is of type
// '123' is an int, so an implicit conversion takes place here: float f = 123;
long aLong = 22; int i1 = aLong; // Error: no implicit conversion from long. int i2 = (int)aLong; // OK: explicit conversion.
Notice also that there is no implicit conversion from floating-point types to
int. For example, the following statement generates a compiler error unless an explicit cast is used:
int x = 3.0; // Error: no implicit conversion from double. int y = (int)3.0; // OK: explicit conversion.
C# Language Specification
We'd love to hear your thoughts. Choose the type you'd like to provide:
Our feedback system is built on GitHub Issues. Read more on our blog.