Quote:
I don'tget it. The only way to get a result of false is by providing a number...
If you mean "providing a number" as in:
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
...
var day = (Days)42;
...
if (Enum.IsDefined(typeof(Days), day)) ...
Then I think you're right: that's the only way of getting a result of
false
(or, for that matter, any other way that gets you to that point).
Personally, I try to avoid
Enum.IsDefined()
and only use it with
Debug.Assert()
and other methods in this latter class. For the release version of the program, I prefer to define extension methods for each enum class (when appropriate) to check for valid values and, sometimes, other invariant rules. Most of the times, by using a
switch
statement. It has proven to be a good technique.
Maybe
Enum.IsDefined()
can prove itself most valuable in other circumstances. Like, for example, general "externalized" validation rules applied to raw input data. I mean, when you want the business rules defined
outside the program, and not hardcoded into it. Just a thought, though.
I hope I made myself clear; it's kind of an abstract idea.
Good question.