Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new IntPtr(0) vs. IntPtr.Zero

Tags:

Is there any difference between the two statements:

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

I have seen many samples that use PInvoke that prefer the first syntax if the myPtr argument is sent by ref to the called function. If I'll replace all new IntPtr(0) with IntPtr.Zero in my application, will it cause any damage?

like image 474
Yuval Peled Avatar asked Feb 18 '09 08:02

Yuval Peled


People also ask

What is IntPtr zero in c#?

When calling the Windows API from managed code, you can pass IntPtr. Zero instead of null if an argument is expected to be either a pointer or a null . For example, the following call to the Windows CreateFile function supplies IntPtr. Zero for the pSecurityAttributes and hTemplateFile argument values. C# Copy.

What is IntPtr 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. IO.


2 Answers

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

As soon as you pass IntPtr.Zero anywhere you'll get a copy, so for variable initialisation it 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 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 have already said.

like image 101
Keith Avatar answered Nov 10 '22 04:11

Keith


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

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

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

like image 24
Richard Szalay Avatar answered Nov 10 '22 02:11

Richard Szalay