C# Native Integer nint — Complete Guide
In this tutorial, you'll learn about C# Native Integer nint. We cover key concepts, practical examples, and best practices.
You write code that needs to match the native pointer size — 32-bit on x86, 64-bit on x64. You use IntPtr with manual conversions, or int on one platform and long on another. Native integers nint / nuint give you a platform-adaptive integer type with full arithmetic support.
Wrong
// Using IntPtr — no direct arithmetic operators
IntPtr ptr = (IntPtr)42;
IntPtr next = ptr + 1; // Error: no operator + for IntPtr
IntPtr next = new IntPtr(ptr.ToInt64() + 1); // Manual conversion
Output: Works, but verbose and error-prone with manual conversions.
Right
nint ptr = 42;
nint next = ptr + 1; // Direct arithmetic, no conversion needed
Console.WriteLine(next); // 43 (on 64-bit) or 43 (on 32-bit)
Output: 43. Native integers support +, -, *, /, %, bitwise operators, and comparison operators.
Use cases:
// Array index with native size
nint index = 0;
while (index < data.Length)
{
Process(data[index]);
index++;
}
// Interop with native code
nint offset = 1024;
byte* ptr = (byte*)buffer + offset;
Prevention
- Use
nintfor pointer arithmetic, size calculations, and interop scenarios. - Use
nintwhen you need the performance of native-sized operations. - Use
intorlongfor general-purpose arithmetic — do not useninteverywhere. - Use
nuintfor unsigned native integers (e.g.,UIntPtrreplacement). - Avoid boxing native integers — they are value types but boxing loses platform awareness.
- Be aware that
nintis 4 bytes on 32-bit and 8 bytes on 64-bit.
Common Mistakes with native integer
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Native integers are used in Durga Antivirus Pro's memory scanning engine for platform-adaptive buffer sizes. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro