Is IntPtr.Zero equivalent to null?

后端 未结 3 1632
鱼传尺愫
鱼传尺愫 2020-12-05 09:41

I am trying to setup ReadFile to run asynchronously and according to MSDN, I need to set lpNumberOfBytesRead to null:

相关标签:
3条回答
  • 2020-12-05 09:45

    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>
    
    0 讨论(0)
  • 2020-12-05 09:56

    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.

    0 讨论(0)
  • 2020-12-05 10:07

    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.

    0 讨论(0)
提交回复
热议问题