C# Can I check if an IntPtr is null?

Guye Incognito picture Guye Incognito · Sep 19, 2014 · Viewed 14.7k times · Source

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
}

Answer

SLaks picture SLaks · Sep 19, 2014

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)