This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Check if an Enumeration Value is Defined

Variables that are declared as enumerated types can contain values that are not defined within the related enumeration. Sometimes it is necessary to check whether a numeric value or a name exists within the list of constants. This tip explains how.

Enum.IsDefined Method

The Enum class is the base type for all enumerated types. It contains a set of methods that can be used to process and query enumerations. One of the static methods of this class is named "IsDefined". This method tests if a particular value or name is defined within an enumeration's list of constants.

The IsDefined method requires two parameters. The first parameter is the type of the enumeration to be checked. This type is usually obtained using a typeof expression. The second parameter is defined as a basic object. It is used to specify either the integer value or a string containing the name of the constant to find. The return value is a Boolean that is true if the value exists and false if it does not.

Testing for Integer Values

The following example shows a sample enumeration and two IsDefined checks. One check looks for a valid value and the other for a non-existent constant:

enum Status
    OK = 0,
    Warning = 64,
    Error = 256

static void Main(string[] args)
    bool exists;

    exists = Enum.IsDefined(typeof(Status), 0);     // exists = true
    exists = Enum.IsDefined(typeof(Status), 1);     // exists = false

Testing for Constant Names

The second example shows two further IsDefined checks. This time the name of the constant is passed to the method within a string. The enumeration declaration is omitted, as it is the same as in the previous sample:

exists = Enum.IsDefined(typeof(Status), "OK");      // exists = true
exists = Enum.IsDefined(typeof(Status), "NotOK");   // exists = false

NB: The test is case-sensitive. In the example, checking for "ok" will return false.


When using an enumeration that holds a bit field, you cannot check for a value that is a combination of two or more constants. If the specified number or string does not exist as a single constant, the return value will be false.

18 October 2008