Skip to main content

How to Check Whether a Value Is Defined in an Enum with Enum.IsDefined in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Casting a number to an enum never fails: (Size)7 is a Size even when no member has the number 7. Enum.IsDefined is the check that tells you whether the value is one of the enum's members.

Microsoft's API reference: Returns a Boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration. The C# guide says when you need it: Be aware that casting an integer to an enum doesn't validate whether the value matches a defined member. Use Enum.IsDefined to check validity when you accept numeric input from external sources.

Syntax​

Syntax
Enum.IsDefined(<value>)
Enum.IsDefined(typeof(<EnumType>), <numberOrName>)
PartWhat it is
Enum.IsDefined(<value>)Takes a value of the enum type and returns true when it's one of the enum's members, otherwise false
typeof(<EnumType>)In the second form, the enum to look in
<numberOrName>In the second form, a number of the enum's number type, usually int, or a member's name as a string

Both forms return a bool. The reference on the second form's result: true if a constant in enumType has a value equal to value; otherwise, false.

The Example​

A console app called EnumIsDefined has a Size enum with the numbers 1, 2 and 3. It treats three numbers as answers from outside the program, such as a form, and checks whether each one is a size.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n EnumIsDefined
cd EnumIsDefined
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/EnumIsDefined/EnumIsDefined.csproj:
Determining projects to restore...
Restored /Users/you/source/EnumIsDefined/EnumIsDefined.csproj (in 40 ms).
Restore succeeded.

dotnet new console -n EnumIsDefined creates a folder named EnumIsDefined with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or EnumIsDefined.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the loop that checks each number:

Program.cs (the check)
// Numbers that came from outside the program, such as a form.
int[] answers = [1, 3, 7];

foreach (int answer in answers)
{
Size size = (Size)answer;

if (Enum.IsDefined(size))
{
Console.WriteLine($"{answer} is {size}");
}
else
{
Console.WriteLine($"{answer} is not a Size (the cast gave {size})");
}
}
  • (Size)answer casts the number to Size. The cast doesn't check the number.
  • Enum.IsDefined(size) returns true when size is one of the members, and false when it's a number without a member.

Then the enum, at the end of the file:

Program.cs (the enum)
enum Size
{
Small = 1,
Medium = 2,
Large = 3,
}

The members have the numbers 1, 2 and 3, so 7 isn't one of them.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
1 is Small
3 is Large
7 is not a Size (the cast gave 7)

macOS-style terminal window titled Terminal — EnumIsDefined showing dotnet run printing 1 is Small, 3 is Large, and 7 is not a Size with the cast giving 7

1 and 3 are members, so they printed as Small and Large. 7 went through the cast without an error and became a Size that prints as 7, and Enum.IsDefined caught it. The C# specification explains why the cast allows it: The set of values of the enum type is the same as the set of values of the underlying type and is not restricted to the values of the named constants.

The Complete File​

macOS-style code window titled Program.cs — EnumIsDefined showing an array of the numbers 1, 3 and 7, a loop that casts each number to Size and prints it when Enum.IsDefined returns true or a not a Size message when it returns false, and the enum Size with Small = 1, Medium = 2 and Large = 3

Program.cs
// Numbers that came from outside the program, such as a form.
int[] answers = [1, 3, 7];

foreach (int answer in answers)
{
Size size = (Size)answer;

if (Enum.IsDefined(size))
{
Console.WriteLine($"{answer} is {size}");
}
else
{
Console.WriteLine($"{answer} is not a Size (the cast gave {size})");
}
}

enum Size
{
Small = 1,
Medium = 2,
Large = 3,
}

Common Mistakes​

MistakeWhat happensDo this instead
Using a cast number without checking it(Size)7 didn't fail: the program carried on with a Size that printed 7Call Enum.IsDefined before you use a number that came from outside the program
Passing the int itself to the one-argument form, as in Enum.IsDefined(answer)error CS0315: The type 'int' cannot be used as type parameter 'TEnum' in the generic type or method 'Enum.IsDefined<TEnum>(TEnum)'. There is no boxing conversion from 'int' to 'System.Enum'.Cast it first, Enum.IsDefined((Size)answer), or use Enum.IsDefined(typeof(Size), answer)
Checking a name with different capitalsEnum.IsDefined(typeof(Size), "small") returned False, while "Small" returned TrueMatch the member's spelling exactly. The reference: The characters in the string must have the same case as the enumeration member name.
Passing a long to the typeof form for an int enumSystem.ArgumentException: Enum underlying type and the object must be same type or object must be a String. Type passed in was 'System.Int64'; the enum underlying type was 'System.Int32'.Pass a number of the enum's own number type, here int

FAQ​

Can I check a name instead of a number?​

Yes, with the typeof form: Enum.IsDefined(typeof(Size), "Large") returned True. The one-argument form takes only a value of the enum: Enum.IsDefined<Size>("Small") didn't build, with error CS1503: Argument 1: cannot convert from 'string' to 'Size'.

Why does int fail when the reference says the type only has to be a struct?​

The reference page shows the one-argument form as IsDefined<TEnum>(TEnum value) where TEnum : struct. The method also requires an enum, as the CS0315 error above says: There is no boxing conversion from 'int' to 'System.Enum'. I reported the missing constraint to the .NET API docs as issue #13401.

Doesn't Enum.TryParse already check the value?​

Not for numbers. Enum.TryParse("7", out Size size) returned True and gave 7, and Enum.IsDefined(size) then returned False. A comment in Microsoft's own sample says the same: It returns false only when the input can't be parsed. Call Enum.IsDefined to validate named members.

Does it work with a Flags enum?​

Only for single members. With [Flags] and the members Cheese = 1 and Ham = 2, Enum.IsDefined(Topping.Cheese) returned True, but Cheese | Ham returned False. The reference: for enumerations that define a set of bit fields, the method determines only whether a single bit field belongs to the enumeration. Use HasFlag for combined values: on Cheese | Ham, HasFlag(Topping.Ham) returned True.

Conclusion​

A cast turns any number into an enum value, named or not. Call Enum.IsDefined(value), or Enum.IsDefined(typeof(MyEnum), number), before you trust a number from outside the program, and handle the false case yourself.

Additional Resources​