Is IntPtr.Zero equivalent to null?

C#File IoAsynchronous

C# Problem Overview


I am trying to setup ReadFile to run asynchronously and according to MSDN, I need to set lpNumberOfBytesRead to null: > "Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results."

For example, if I have the following:

  [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  public static extern bool ReadFile(
     IntPtr hFile,
     out byte[] aBuffer,
     int cbToRead,
     IntPtr cbThatWereRead,
     ref OVERLAPPED pOverlapped
  );

and I call it like this (with the intention of having the 4th parameter being null):

Win32API.ReadFile(readHandle, out data_read, Win32API.BUFFER_SIZE, IntPtr.Zero, ref over_lapped);

will that be the same as calling it with null? If not, what should I change in the declaration or in the function call itself?

I was also curious if I should be using SafeHandle or HandleRef instead of IntPtr for the hFile reference? I know to make sure that I close the handle with CloseHandle(IntPtr) when I'm done with it, just not sure if there is any othe reason to use the other two options over IntPtr. I am also tryingn to avoid using unsafe code.

EDIT: As it turns out, I shouldnt be setting the fourth parameter to IntPtr.Zero anyway, because even though I am running asynchronously, it could still return right away. See Asynchronous Disk I/O. Ahh, I love contradicting stories.

C# Solutions


Solution 1 - C#

For P/Invoke purposes like you've listed, you should use IntPtr.Zero in place of NULL. Note that this is not equivalent to the C# null keyword, however.

Solution 2 - C#

You cannot assign null to a value-type. A reference-type can be null, as in, not referring to an object instance, but a value-type always has a value.

IntPtr.Zero is just a constant value that represents a null pointer.

Solution 3 - C#

Be aware that there is a bug (feature??) in C# >= 2.0, where

if (IntPtr.Zero == null)
{
    // Won't enter here
}

will compile correctly, but it won't ever enter in the if.

I opened an issue on the github of roslyn and they replied that they won't fix it because there are projects that are built with warnings-as-errors. Still there is a partial fix for this: there is a strict compilation mode that generates this warning:

<Features>strict</Features>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSwDevMan81View Question on Stackoverflow
Solution 1 - C#MichaelView Answer on Stackoverflow
Solution 2 - C#Yannick MottonView Answer on Stackoverflow
Solution 3 - C#xanatosView Answer on Stackoverflow