Skip to content

Native integers C# 9.0new scenariostype safety

Provide architecture-specific integer types.

When working with unmanaged libraries an integers size might be dependant on the processor architecture it is compiled for. For example, iOS's NSInteger can be either 32-bit or 64-bit.

C# 9.0 introduces the nint and nuint types that behave much as int and uint on 32-bit systems and as long and ulong on 64-bit systems.

Code

C#
[DllImport("math.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
static extern nint Add(nint a, nint b);

var result = Add(1, 2);
C#
#if X64

[DllImport("math.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
static extern long Add(long a, long b);

#else

[DllImport("math.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
static extern int Add(int a, int b);

#endif

var result = Add(1, 2);

Notes

While C# already has IntPtr to provide similar architecture-specific behavior it is intended for memory addressing and has intentionally limited conversion and mathematical operators.

More information