19

I have an IntPtr field in my C# class.
It holds a reference to an object in a C++ library.

protected IntPtr ThingPtr;

At some stage I may or may not initialise it.

ThingPtr = FunctionInMyCplusplusLibrary();

I'm wondering if checking whether it is null makes sense in this context (to check whether it has been intialised or not)

if(ThingPtr == null)
{
    //Do stuff
}
Guye Incognito
  • 2,726
  • 6
  • 38
  • 72
  • 1
    Never. ever. presume ANYTHING to be initialized. So yes, it does make complete sense! –  Sep 19 '14 at 15:29
  • 1
    An `IntPtr` can never be `null`. Use `ThingPtr == IntPtr.Zero` instead. – D Stanley Sep 19 '14 at 15:31
  • Not exactly a duplicate but this is an answer that you should read http://stackoverflow.com/questions/1456861/is-intptr-zero-equivalent-to-null – Steve Sep 19 '14 at 15:31
  • Structs are value types and cannot be null while objects are reference types and can be null. – Sam Sep 19 '14 at 15:32

3 Answers3

63

IntPtr is a value type and cannot be null.

You want to check whether it has a value of (address) 0:

if (ThingPtr == IntPtr.Zero)
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • An alternative is default(IntPtr) which I suspect is equivalent to IntPtr.Zero. If you want to specify the default value for a parameter, IntPtr.Zero won't work, but you can specify default(IntPtr), for example void TestMethod ( IntPtr p = default(IntPtr) ) – Phil Jollans Jul 22 '21 at 15:19
4

IntPtr is a struct it can never be null, your library may return the equivalent of null but I expect that would be zero.

Jaycee
  • 3,098
  • 22
  • 31
3

You can use IntPtr.Zero for null, however it's not equivalent to C# null value.

brz
  • 5,926
  • 1
  • 18
  • 18