user541686
user541686

Reputation: 210525

Is zero ever a valid handle?

There is a SafeHandleZeroOrMinusOneIsInvalid class in the .NET Framework, as well as a SafeHandleMinusOneIsInvalid class.

Why is this? In which situations is zero ever a valid handle?

Upvotes: 11

Views: 3506

Answers (3)

MartinStettner
MartinStettner

Reputation: 29174

As additional lecture to the other answers, see this OldNewThing blog entry about inconsistent handle return values.

Upvotes: 7

BrendanMcK
BrendanMcK

Reputation: 14498

I think you're reading too much into the name: all this means is that some APIs by convention return 0 to indicate failure, others return -1. For an API that returns -1, this doesn't mean that 0 will ever be a valid handle, just that the API returns -1 to indicate failure.

So this is really about the value that is typically used by an API to indicate failure; it doesn't say anything about whether any other handle values are valid or not for any given set of APIs.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

As put forth by Microsoft in their documentation (and demonstrated in description by Joshua,) it is implementation dependant, so to speak:

It describes the format of an invalid handle.

For example, some handles use -1 as an invalid handle value, while others use 0. Further derivations of this class (for example, file or registry handles) can specialize this further. See the SafeFileHandle class for an example of a class that derives from SafeHandleZeroOrMinusOneIsInvalid.

Upvotes: 4

Related Questions