Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
The .Net 4.5 Enum.IsDefined definition includes the following two statements which appear highly ambiguous to me.

Definition
C#
public static bool IsDefined(
    Type enumType,
    Object value
)

true if a constant in enumType has a value equal to value; otherwise, false.

Exceptions
ArgumentException

The type of value is an enumeration, but it is not an enumeration of type enumType.
-or-
The type of value is not an underlying type of enumType.


I don'tget it. The only way to get a result of false is by providing a number, any attempt to provide anything else will provide will either be true or will throw an exception.

Seems like an over-complicated way of telling the userof the eumeration exactly what error they've made and by consequence less than obvious.

Ironically, feedback via an enumeration would have seemed more comprehensible.
Have I understood this correctly?

Thanks,
M
Posted

1 solution

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:
C#
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.
 
Share this answer
 
v2
Comments
M-Badger 25-Aug-13 13:16pm    
Thanks, I've started doing a thorough examination of how it works in a variety of circumstances.
My question here was linked to the one linked below and the implementation of a Switch...Case...Default
http://www.codeproject.com/Questions/639070/Exceptions-for-Enum-Method-Parameters

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900