Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
integer
native
communitycreator

What are native-sized integers in C#?

Siddharth Singh

What are native-sized integers?

A native-sized integer is an integer whose size is dependent on the platform where it is used.

  • For an application running as a 64-bit process, the native-sized integer size is 64-bits(8 Bytes).
  • For an application running a 32-bit process, its size is 32-bits or 4 bytes.

Native-sized integers in C#

C# supports native-sized integers, starting from the 9.0 version, with the below keywords:

nint

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

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

Why are native-sized integers used?

Native-sized integers are used to optimize performance. They are mainly found in:

  • Low-level libraries
  • Interop scenarios where C# code needs to call operating system APIs or other libraries that use machine word size integers
  • Performance optimization for scenarios where heavy integer calculations are needed

RELATED TAGS

c#
integer
native
communitycreator
RELATED COURSES

View all Courses

Keep Exploring