C# Reference ยท Keywords and Statements
The enum keyword
Reference for the C# enum keyword: declare named constants, choose the underlying type, combine values with [Flags], and parse and validate safely.
enum declares a value type made of named integral constants. Use it when a value must be one of a fixed set of choices: a day of the week, a log level, a state in a workflow. Names make code readable and let the compiler catch typos.
Behind each name is a number. By default the underlying type is int and the first member is 0, each following member one higher. An enum value is not restricted to the declared names: any number of the underlying type can be cast into it, so validate input from outside your program.
enum Level { Low, Medium = 5, High } // 0, 5, 6
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
[attributes] [modifiers] enum Name [: underlyingType] { Member1, Member2 = constant, Member3, }
The underlying type can be byte, sbyte, short, ushort, int (default), uint, long or ulong.
| Useful members | Description |
|---|---|
Enum.Parse<T>(string, bool) |
Converts a name or number to T; throws ArgumentException or OverflowException on failure. |
Enum.TryParse<T>(string, out T) |
Like Parse, returns false instead of throwing. Accepts numbers that are not defined. |
Enum.IsDefined(type, value) |
Checks whether a value has a name. |
Enum.GetValues<T>() / GetNames<T>() |
All members, ordered by value. |
value.HasFlag(flag) |
Tests flag bits. |
Errors: enum member values must fit the underlying type (compile error otherwise). Casting an undefined number does not throw.
Usage notes
- Validate untrusted numbers.
(Level)42compiles and runs. UseEnum.IsDefined, or have aswitchexpression with a throwing default branch. - Flags enums: use powers of two (
1, 2, 4, 8or1 << n), add[Flags]soToStringprints combinations, and defineNone = 0. - Default value:
default(Level)is 0, whether or not a member has that value. Give 0 a meaningful member. - No methods inside enums, but extension methods can add behavior.
- Comparison: enums support
==,<,>, bitwise operators and++(they act on the underlying value). - Switching over an enum is not checked for exhaustiveness the way other types are: a
switchexpression warns (CS8524) if the unnamed values are not handled. - Serialization: names are more stable than numbers; renaming a member can break stored data.
Related
kw-switch,op-bitwise,kw-const- Tutorials: Enums, Constants