What is int and uint
Both Int (int) and UInt (uint) are both number types known as integers, these variables hold 32 bits (4 bytes) of data. The uint
is unsigned and cannot hold negative numbers, while int
is signed and can hold both negative and positive numbers.
Data Type | Range | Struct |
---|---|---|
int | -2,147,483,648 to 2,147,483,647 | System.Int32 |
uint | 0 to 4,294,967,295 | System.UInt32 |
int and uint are types of integers and are aliases for System.Int32
and System.UInt32
.
By default, the data type int
cannot be null. However, you can make it nullable if required using int?
.
Usage of the variable type
It is recommended to declare the variable using int
or uint
rather than their struct type keyword, but either will work. Below is an example of assigning integer values:
int a = 0;
System.Int32 b = 0;
uint c = 0;
System.UInt32 d = 0;
You can also just use Int32
or UInt32
, but you must include using System;
(unless using .net 8) at the top of your namespace, Visual Studio will usually highlight this for you.
using System; // not needed in .net 8
namespace Test
{
class Program
{
static void Main(string[] args)
{
int a = 0;
Int32 b = 0;
uint c = 0;
UInt32 d = 0;
}
}
}
Using int
makes your code simpler and is considered the standard. You can also use the var
keyword, but it defaults to int
, so explicit casting is needed for uint
.
int a = 0;
var b = 0; // This defaults to int (Int32).
var c = (int)0; // 'var' is auto set to type 'int', so casting is not needed
var d = (uint)0; // casting is required as default is int
var e = new uint(); // This is uint with default value of 0
The same applies to the uint
type.
Properties of int and uint
There are two properties you can use: MaxValue
and MinValue
.
Type | MinValue | MaxValue |
int | -2,147,483,648 | 2,147,483,647 |
uint | 0 | 4,294,967,295 |
Code example:
class Program
{
static void Main(string[] args)
{
int intMinValue = int.MinValue;
int intMaxValue = int.MaxValue;
uint uintMinValue = uint.MinValue;
uint uintMaxValue = uint.MaxValue;
Console.WriteLine("int MinValue:" + intMinValue.ToString());
Console.WriteLine("int MaxValue:" + intMaxValue.ToString());
Console.WriteLine("uint MinValue:" + uintMinValue.ToString());
Console.WriteLine("uint MaxValue:" + uintMaxValue.ToString());
Console.ReadKey();
}
}
Output produced from the above code sample:
As shown above, MaxValue
assigns the maximum value the variable type can hold, and MinValue
outputs the smallest value.
Overflow
By default, overflow for short types are disabled. See Overflow Exception.