Search code examples
c#safehandle

What's the purpose of invalidHandleValue in SafeHandle?


The SafeHandle constructor takes an invalidHandleValue. What is it used for if you have to implement IsInvalid anyway because it has no idea which member variable holds the pointer [I didn't know it implemented the handle member variable for you]?


Solution

  • Looking at it in DotPeek, I see that it is used only to initialize the protected IntPtr handle member variable.

    protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
    {
      this.handle = invalidHandleValue;
      ...
    }
    

    I'd say that the logic for this is something like:

    • They want to guarantee that the handle member variable is initialized to something, so they make you pass the invalid value.
    • There might be additional logic you want to test for in IsInvalid, so they don't bother to provide a default implementation (which would require saving the passed invalidHandleValue in the ctor as well.)