nint and nuint types (C# reference)

Starting in C# 9.0, you can use the nint and nuint keywords to define native-sized integers. These are 32-bit integers when running in a 32-bit process, or 64-bit integers when running in a 64-bit process. They can be used for interop scenarios, low-level libraries, and to optimize performance in scenarios where integer math is used extensively.

The native-sized integer types are represented internally as the .NET types System.IntPtr and System.UIntPtr. Unlike other numeric types, the keywords are not simply aliases for the types. The following statements are not equivalent:

nint a = 1;
System.IntPtr a = 1;

The compiler provides operations and conversions for nint and nuint that are appropriate for integer types.

Run-time native integer size

To get the size of a native-sized integer at run time, you can use sizeof(). However, the code must be compiled in an unsafe context. For example:

Console.WriteLine($"size of nint = {sizeof(nint)}");
Console.WriteLine($"size of nuint = {sizeof(nuint)}");

// output when run in a 64-bit process
//size of nint = 8
//size of nuint = 8

// output when run in a 32-bit process
//size of nint = 4
//size of nuint = 4

You can also get the equivalent value from the static IntPtr.Size and UIntPtr.Size properties.

MinValue and MaxValue

To get the minimum and maximum values of native-sized integers at run time, use MinValue and MaxValue as static properties with the nint and nuint keywords, as in the following example:

Console.WriteLine($"nint.MinValue = {nint.MinValue}");
Console.WriteLine($"nint.MaxValue = {nint.MaxValue}");
Console.WriteLine($"nuint.MinValue = {nuint.MinValue}");
Console.WriteLine($"nuint.MaxValue = {nuint.MaxValue}");

// output when run in a 64-bit process
//nint.MinValue = -9223372036854775808
//nint.MaxValue = 9223372036854775807
//nuint.MinValue = 0
//nuint.MaxValue = 18446744073709551615

// output when run in a 32-bit process
//nint.MinValue = -2147483648
//nint.MaxValue = 2147483647
//nuint.MinValue = 0
//nuint.MaxValue = 4294967295

Constants

You can use constant values in the following ranges:

Conversions

The compiler provides implicit and explicit conversions to other numeric types. For more information, see Built-in numeric conversions.

Literals

There's no direct syntax for native-sized integer literals. There's no suffix to indicate that a literal is a native-sized integer, such as L to indicate a long. You can use implicit or explicit casts of other integer values instead. For example:

nint a = 42
nint a = (nint)42;

Unsupported IntPtr/UIntPtr members

The following members of IntPtr and UIntPtr aren't supported for nint and nuint types:

C# language specification

For more information, see the C# language specification and the Native-sized integers section of the C# 9.0 feature proposal notes.

See also