Search code examples
c#nullintptr

C# Can I check if an IntPtr is null?


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
}

Solution

  • 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)