[ACCEPTED]-new IntPtr(0) vs. IntPtr.Zero-pinvoke

Accepted answer
Score: 26

IntPtr is a value type, so unlike String.Empty there's relatively 6 little benefit in having the static property 5 IntPtr.Zero

As soon as you pass IntPtr.Zero anywhere you'll get 4 a copy, so for variable initialisation it 3 makes no difference:

IntPtr myPtr = new IntPtr(0);
IntPtr myPtr2 = IntPtr.Zero;

//using myPtr or myPtr2 makes no difference
//you can pass myPtr2 by ref, it's now a copy

There is one exception, and 2 that's comparison:

if( myPtr != new IntPtr(0) ) {
    //new pointer initialised to check
}

if( myPtr != IntPtr.Zero ) {
    //no new pointer needed
}

As a couple of posters 1 have already said.

Score: 7

They are functionally equivalent, so it 7 should cause no problems.

IntPtr.Zero represents the 6 default state of the structure (it is declared 5 but no constructor is used), so the default 4 value of the intptr (void*) would be null. However, as (void*)null and 3 (void*)0 are equivalent, IntPtr.Zero == new IntPtr(0)

Edit: While they are equivalent, I 2 do recommend using IntPtr.Zero for comparisons since 1 it simply is easier to read.

Score: 5

The use of IntPtr.Zero will allow you to avoid a new 3 instance of IntPtr.

from msdn:

Use this field to efficiently determine 2 whether an instance of IntPtr has been 1 set to a value other than zero

Score: 1

What happens if you pass IntPtr.Zero by ref, and the 6 recipient tries to modify the reference? From 5 that moment forth, would IntPtr.Zero != new IntPtr(0), or would the 4 recipient receive some kind of exception 3 upon trying to make the change?

I'm not sure 2 about this, but it seems like a reasonable 1 explanation.

Score: 0

The JITter can inline IntPtr.Zero the same 1 way it inlines IntPtr.Size.

More Related questions