mpen
mpen

Reputation: 282995

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]?

Upvotes: 2

Views: 531

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127583

It is the default value of handle for when you call new SafeHandleDerivedClass() (the derived class may call base.SetHandle(someValue) in the constructor, but before that call the value will be whatever was passed in to the base class constructor).

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137448

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.)

Upvotes: 2

Related Questions