Back to results for “JSON”
C# › Enums & Flags

How do you safely validate that an enum value received from external input (like deserialized JSON or a database) is actually a DEFINED member, given that enums don't enforce this by default?

Advanced

Answer

Since C# enums are just named integers, a value like (Permissions)999 compiles and runs fine even though it doesn't correspond to any defined member (or valid flag combination) — use Enum.IsDefined() for simple enums, or a manual bitwise check against a computed 'all valid flags' mask for [Flags] enums, to validate untrusted input before trusting it.
public enum Status { Active = 0, Inactive = 1 }
int rawValue = 99; // e.g., from untrusted deserialized JSON
var status = (Status)rawValue; // compiles and runs, but is INVALID
bool isValid = Enum.IsDefined(typeof(Status), status); // false -- correctly caught
Real-world example Validating a status or category field parsed from external API input before it's trusted and used in business logic.

Common follow-ups: Why doesn't Enum.IsDefined() work correctly out of the box for validating combined [Flags] enum values?