programming
enum
number checking
tutorial
coding

How to check If a Enum contain a number?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Checking whether a number belongs to an enum is a frequent validation task in APIs, parsers, and UI binding logic. In C#, the straightforward tool is Enum.IsDefined, but using it blindly can produce incorrect results for [Flags] enums or string-parsed values. You also need to decide whether numeric inputs must match named constants exactly or whether combined flag values are allowed. This article explains reliable enum validation patterns for integers, nullable inputs, and flags-based scenarios, with practical code examples.

Core Sections

1. Basic check with Enum.IsDefined

For standard enums where only declared values are valid:

csharp
1public enum Status
2{
3    Pending = 1,
4    Approved = 2,
5    Rejected = 3
6}
7
8int incoming = 2;
9bool valid = Enum.IsDefined(typeof(Status), incoming);
10Console.WriteLine(valid); // true

This is clear and safe for non-flags enums.

2. Generic helper for typed validation

Use a generic method to avoid repeating reflection calls.

csharp
1public static bool IsDefinedEnumValue<TEnum>(int value) where TEnum : struct, Enum
2{
3    return Enum.IsDefined(typeof(TEnum), value);
4}
5
6bool ok = IsDefinedEnumValue<Status>(3);

This improves readability in controllers and mapping layers.

3. Parsing and validating external input

If you receive numeric strings, parse first and validate explicitly.

csharp
1string raw = "4";
2if (int.TryParse(raw, out int num) && Enum.IsDefined(typeof(Status), num))
3{
4    Status s = (Status)num;
5    Console.WriteLine(s);
6}
7else
8{
9    Console.WriteLine("Invalid status value");
10}

Do not cast before checking validity, or you may carry invalid enum values silently.

4. Special case: [Flags] enums

Enum.IsDefined does not treat arbitrary bit combinations as valid unless the exact numeric combination is declared. For flags, validate bit masks instead.

csharp
1[Flags]
2public enum Permission
3{
4    None = 0,
5    Read = 1,
6    Write = 2,
7    Execute = 4
8}
9
10public static bool IsValidPermission(int value)
11{
12    int all = (int)(Permission.Read | Permission.Write | Permission.Execute);
13    return value >= 0 && (value & ~all) == 0;
14}

This accepts combinations like Read | Write even if not explicitly named.

5. API boundary recommendations

At API boundaries, reject invalid numeric enum values early and return a clear error payload. This keeps invalid states from propagating into business logic and persistence layers.

Validation and production readiness

A reliable implementation should include more than a working snippet. Add a small reproducible dataset or input fixture that exercises expected behavior and edge cases, then codify it in automated tests. Include at least one “happy path,” one malformed input case, and one boundary condition so regressions are caught early. Instrument key steps with structured logs or metrics to make failures diagnosable in runtime environments, not just local development. If performance is relevant, keep a lightweight benchmark that can be rerun after refactors to ensure behavior stays within budget.

Operationally, document assumptions near the code: required library versions, environment variables, timezone/locale expectations, and failure handling strategy. For team workflows, add one integration test that mirrors real usage rather than only unit-level checks. This reduces drift between example code and production behavior. Treat these checks as part of feature completion, because most long-term issues are caused by unvalidated assumptions rather than syntax errors.

Common Pitfalls

  • Casting int to enum directly and assuming the value is valid.
  • Using Enum.IsDefined for [Flags] enums when combined values should be accepted.
  • Accepting negative or overflowed numeric values without explicit checks.
  • Parsing strings to enum names when input contract is numeric codes.
  • Validating only at UI layer and skipping server-side enum validation.

Summary

To check whether an enum contains a number in C#, use Enum.IsDefined for standard enums and bitmask validation for [Flags] scenarios. Parse external input carefully, validate before casting, and enforce rules at system boundaries. With explicit validation strategy, enum values remain trustworthy throughout your application.


Course illustration
Course illustration

All Rights Reserved.