A native-sized integer is an integer whose size is dependent on the platform where it is used.
C# supports native-sized integers, starting from the 9.0 version, with the below keywords:
nint is used to define a native-sized signed integer, and is internally represented as the .NET type System.IntPtr
.
For example:
nint p = -1;
We can get the minimum and maximum values at runtime using the MinValue and MaxValue static properties with the nint
keyword, e.g., nint.MinValue
nuint is used to define a native-sized unsigned integer, and is internally represented as the .NET type System.UIntPtr
.
For example:
nuint p = 10;
We can get the minimum and maximum values at runtime using the MinValue and MaxValue static properties with the nuint
keyword, e.g., nuint.MinValue
and nuint.MaxValue
.
sizeof()
can be used in an unsafe context to get the size of the native-sized integers at runtime.
Console.WriteLine($"Native integer size = {sizeof(nint)}");
);
// 64-bit process output
//Native integer size = 8
// 32-bit process output
//Native integer size = 4
Native-sized integers are used to optimize performance. They are mainly found in: