When working with unmanaged libraries an integer's size might be dependent 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
csharp
var result = NativeMath.Add(1, 2);
static class NativeMath
{
[DllImport("math.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern nint Add(nint a, nint b);
}csharp
var result = NativeMath.Add(1, 2);
// Needed a separate build per architecture, with X64 defined by hand
static class NativeMath
{
#if X64
[DllImport("math.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern long Add(long a, long b);
#else
[DllImport("math.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
#endif
}Notes
- While C# already has IntPtr to provide similar architecture-specific behavior it is intended for memory addressing and had intentionally limited conversion and mathematical operators.
- From C# 11 (on .NET 7 and later)
nintandnuintare simply aliases forIntPtrandUIntPtr, which gained full numeric operators.