Enums in C#
Define type-safe constants with enums, use [Flags] for bitwise enums, parse and convert enums, and combine with switch expressions for exhaustive handling.
Enum Basics
What is an Enum?
An enum is a value type that represents a fixed set of named integer constants. It prevents invalid values that plain `string` or `int` constants would allow.
Explicit Values & Underlying Type
You can assign explicit integer values to enum constants. The underlying type can also be changed to `byte`, `short`, `long`, etc.
Enum in switch Expression
Enums work perfectly with switch expressions. The compiler warns if you miss a case, making handling exhaustive.
Iterating & Parsing Enums
Iterating All Values
`Enum.GetValues<T>()` (C# 7.3+ with generic overload in .NET 5+) returns all constants in declaration order.
Parsing & TryParse
`Enum.Parse<T>(string)` converts a string to the matching enum constant. `Enum.TryParse<T>` is the safe version that does not throw.
Validating Enum Values
`Enum.IsDefined<T>(value)` checks whether an integer or string corresponds to a declared constant — useful for validating untrusted data.
[Flags] Enums
Bitwise Flags with [Flags]
The `[Flags]` attribute marks an enum whose constants are powers of 2. You can combine them with `|` and test membership with `HasFlag()` or `&`.
Flags in Practice — File Access
Flags enums are used throughout .NET itself: `FileAccess`, `FileShare`, `RegexOptions`, `BindingFlags`, etc. The same pattern works in your own domain code.
Adding Behaviour to Enums
Extension Methods on Enums
Because C# enums are value types (not classes), you cannot add methods inside the enum body. Instead, create a static class with extension methods.
Enum as Dictionary Key
Enums make excellent dictionary keys — they are value types with O(1) equality and no hashing overhead. This replaces Java's `EnumMap`.
Enum Best Practices
Naming & Design Conventions
Follow .NET conventions: PascalCase for both the enum type and its constants. Singular names for regular enums, plural names for [Flags] enums.
Casting Pitfall — Out-of-Range Values
Casting any integer to an enum in C# always succeeds — even if the value is not a declared constant. Always validate external values with `Enum.IsDefined`.