why is it not possible to compare IntPtr.Zero and default(IntPtr)?

1.3k Views Asked by At

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
1

There are 1 best solutions below

0
On BEST ANSWER

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());