When a numeric value is passed to a method that accepts an enumeration type, it is possible that the numeric value does not exist in the parameter that accepts the enumeration value. You want to perform a test before using this numeric value to determine whether it is indeed listed in this enumeration type.
The static Enum.IsDefined method determines whether an enumeration value actually exists within an enumeration of a particular type. Enum.IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not.
The Enum.IsDefined method should be used to determine whether a valid enumeration value has been passed to any method that accepts an enumeration value as a parameter. In particular, this Enum.IsDefined should always be used whenever the method is visible to external objects. Any external object can invoke methods with public visibility; therefore, any enumerated value passed in to this method should be screened before it is actually used. Methods with internal, protected, and internal protected visibility have a much smaller scope than public methods but could still suffer from the same problems as the public methods. Methods with private visibility may not need this extra level of protection. Use your own judgment on whether to use Enum.IsDefined to evaluate enumeration values passed in to private methods. Note that calling this method adds a little overhead to your method. This slight performance hit can be magnified if this method is called many times throughout your application.
For example, you have the enumeration below:
enum TrafficLight
{
Red = 1, Yellow = 2, Green = 4
}
You can create a method to validate the enumeration value, like below:
public bool IsValidTrafficLight(TrafficLight tl) { if (Enum.IsDefined(typeof(TrafficLight), tl) { return true; } else { return false; } }
Popularity: 2% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply