Reputation: 105097
This should be simple: I see everywhere people use IntPtr
, is there any reason I should use UIntPtr
instead?
Upvotes: 14
Views: 7129
Reputation: 493
There is a big difference.. For example, on a 32-bit application, new UIntPtr(0xC01E0001)
results in a pointer at 3223191553, but IntPtr(0xC01E0001)
results in a System.OverflowException: "Arithmetic operation resulted in an overflow". That is, because 0xC01E0001 is greater than MaxValue for Int32.
So if one still wants such a pointer, a negative integer needs to be used as internal value for IntPtr, like
unchecked((IntPtr)(int)0xC01E0001)
To answer your question: For values greater than Int32.MaxValue it is easier and somehow cleaner to use UIntPtr. It is probably always the best solution, since pointers are always considered unsigned.
Upvotes: 3
Reputation: 48949
Well according to Microsoft UIntPtr
is provided mostly for architectural symmetry. Another interesting point is that UIntPtr
is not CLS compliant.
On the surface it would seem that IntPtr is the preferred option. However, if you know you will be doing pointer arithmetic then UIntPtr may be a better choice since in the off chance there were some obscure problem dealing with negative values.
Upvotes: 9
Reputation: 116977
Doesn't seem like there would be a good reason to. From the docs:
Remarks
...
The IntPtr type is CLS-compliant, while the UIntPtr type is not. Only the IntPtr type is used in the common language runtime. The UIntPtr type is provided mostly to maintain architectural symmetry with the IntPtr type.
Upvotes: 8