I just learned the hard way that IntPtr.Zero cannot be compared to default(IntPtr). Can someone tell me why?
IntPtr.Zero == new IntPtr(0) -> "could not evaluate expression"
IntPtr.Zero == default(IntPtr) --> "could not evaluate expression"
IntPtr.Zero == (IntPtr)0 -> "could not evaluate expression"
IntPtr.Zero.Equals(IntPtr.Zero) --> "Enum value was out of legal range" exception
IntPtr.Zero.Equals(default(IntPtr)) --> "Enum value was out of legal range" exception
IntPtr.Zero == IntPtr.Zero --> true
new IntPtr(0) == new IntPtr(0) --> true
Although Zero is equivalent to null for Windows API functions with parameters or return values that can be either pointers or null , Zero is not equivalent to null . Passing null to the IntPtr. Zero. Equals method always returns false .
An IntPtr is a value type that is primarily used to hold memory addresses or handles. A pointer is a memory address. A pointer can be typed (e.g. int* ) or untyped (e.g. void* ).
The IntPtr type can be used by languages that support pointers and as a common means of referring to data between languages that do and do not support pointers. IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.
Works for me in compiled code in VS 2010, VS 2008, VS 2005 SP1, Mono 1.2.6. Managed to reproduce both problems in the watch window of Visual Studio 2005 only (I tried with VS 2005 SP1), the compiled code works as expected. (By both problems I mean Problem 1: "Could not evaluate expression", Problem 2: "Enum value was out of legal range".) Thus, as was pointed out by some of the comment authors, it is a VS 2005 watch window bug that you stumbled upon. It is surprisingly hard to quickly find a link to the relevant bug report...
Otherwise in such cases I'd start from reflection to see what types you try to compare (replace Console.Out with any meaningful stream you have access to):
Console.WriteLine("new IntPtr(0) type is: " + new IntPtr(0).GetType());
Console.WriteLine("IntPtr.Zero type is: " + IntPtr.Zero.GetType());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With