Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 441
John Smith Avatar asked Jun 06 '12 14:06

John Smith


People also ask

Is IntPtr zero the same as null?

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 .

How does IntPtr work?

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* ).

What is the use of IntPtr in C#?

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.


1 Answers

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());
like image 80
jpe Avatar answered Sep 27 '22 16:09

jpe