Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 182 ยท Variables and Types

Enums and Flags

Learn C# enums - declaring named constants, underlying types, Enum.Parse and TryParse, GetValues, [Flags] with bitwise operations, switch expressions and the undefined value pitfall.

Programs are full of choices from a small, fixed list: the days of the week, the state of an order (pending, shipped, delivered), a file's permissions, the direction a character is facing. You could store these as plain numbers (2 means shipped) or strings ("shipped"), but then nothing stops you from writing 7 or "shiped", and nobody reading the code knows what 2 means.

An enum (short for enumeration) gives each choice a readable name while the compiler checks that you use them correctly. Under the hood an enum is just an integer, which makes it small and fast. In this lesson you declare enums, control their numbers, convert between text, numbers and names, combine options with [Flags] and bit operations, use enums in switch expressions, and learn the main pitfall: C# lets you store numbers in an enum variable that have no name.

Declaring an enum

An enum is a type of its own. List the names inside braces, separated by commas:

C# Your first enum

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.

By default the first name gets the value 0, the next 1, and so on. Printing an enum value shows its name, which is a big advantage over raw integers in logs and error messages. A trailing comma after the last member is allowed and makes edits and diffs cleaner. Enum names use PascalCase, and the enum type is named with a singular noun (Season, not Seasons), except for [Flags] enums, which take a plural.

An enum is a value type and the default value of any enum field or array element is 0, whether or not a member has that value. So put a sensible "none/unknown" choice at 0 (Unknown, None) when "unset" is possible.

Choosing the numbers

You can assign values explicitly. Names after an explicit value continue counting from it. This is how you match numbers from a database, a file format or a network protocol.

C# Explicit values

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.

The underlying type defaults to int. You can pick another integral type (byte, sbyte, short, ushort, int, uint, long, ulong) after a colon. Use a smaller type only when you store huge arrays of the enum or must match a file layout; otherwise int is simplest. Notice HttpStatus.Gone has the value 405 because it simply follows NotFound, and that (HttpStatus)500 turns the number back into a name.

Converting between enums, names and numbers

You want Code
number from enum (int)Season.Winter
enum from number (Season)3 (not checked!)
text of the name season.ToString() or nameof(Season.Winter)
enum from text (may throw) Enum.Parse<Season>("Winter")
enum from text (safe) Enum.TryParse<Season>("Winter", out var s)
all members Enum.GetValues<Season>()
all names Enum.GetNames<Season>()
is this value declared? Enum.IsDefined(season)
C# Parse, TryParse and enumerating

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.

Look closely at the results for "3" and "42" (and note that the trailing space in "autumn " is ignored). Enum.TryParse accepts text that is a number as well as a name: "3" becomes Winter, and it happily returns true for "42" even though no Season has the value 42. That's the pitfall in the next section. Use Enum.IsDefined afterwards if only declared members are valid.

The undefined value pitfall

Because an enum is "an integer with names", the compiler lets you cast any integer to it, and it never checks the range. (Season)42 is legal and produces a value with no name.

C# Undefined enum values slip through

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.

Two defenses. First, always give a switch over an enum a final _ arm that throws; the compiler warns (CS8509) if you forget it, since it knows the value might not be one of the named members. Second, validate numbers or text that come from outside with Enum.IsDefined. Inside your own code, passing only named members, you don't need that check.

switch expressions with enums

Enums and switch expressions fit together nicely: each arm maps one member to a result. Add a when guard or combine members with or.

C# Enums in a switch expression

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.

Next to the switch statement, enums are a natural key for a Dictionary<OrderState, ...>, or an array indexed by (int)state when the values are small consecutive numbers. The full rules of switch are in switch Statements and Expressions.

[Flags]: combining options

Sometimes a value is not one of several choices but any combination of them: a file can be readable and writable; a pizza can have cheese and mushrooms and olives. A flags enum gives each option its own bit, so a single integer can hold all the combinations. Apply the [Flags] attribute and make the values powers of two (1, 2, 4, 8, ...). You can use the shift operator 1 << n to write them.

C# A [Flags] enum with bit operations

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.

The three operators you need:

  • | adds a flag: p |= Permissions.Execute.
  • & ~ removes a flag: p &= ~Permissions.Write.
  • & tests a flag: (p & Permissions.Write) != 0, or p.HasFlag(Permissions.Write), which is easier to read and, since .NET Core 2.1, as fast.

Always include None = 0. Notice how printing works: when a declared member has exactly the combined value (ReadWrite), its name is printed; otherwise the names of the set bits are joined (Read, Execute). Without [Flags] the enum would still compile, but an undeclared combination would print as a bare number such as 5, which makes logs far less useful. Remember that [Flags] does not give you the powers of two: you must write them yourself, otherwise Read = 1, Write = 2, Execute = 3 would make Execute overlap Read | Write.

Flags need distinct bits. If you added a member such as Other = 3 to the Permissions enum, (p & Permissions.Other) != 0 would be true for a value that has only Read or only Write, because 3 overlaps both bits. Use named combinations (ReadWrite = Read | Write) instead of magic numbers, and use 1 << 0, 1 << 1, 1 << 2 when the list grows long.

Enum helpers and extension methods

An enum cannot contain methods. When you need behavior (a display name, a color, a conversion), write a static helper or an extension method. This keeps the enum itself tiny.

C# Behavior next to an enum

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.

When the data per member gets bigger (a name, a price, a rule), consider a small class or record with static instances ("smart enum") or a lookup table instead of an ever-growing switch. Enums are best when the set is closed, changes rarely and each member is just a label.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the numeric value of Gone in enum S { A = 5, B, Gone }?

    A is 5, B continues from the previous member and is 6, and Gone is 7.
  2. 2. What does (Season)42 do when Season has only four members?

    C# does not range-check casts to an enum. Use Enum.IsDefined to validate numbers from outside.
  3. 3. Which expression removes the Write flag from p?

    AND with the complement keeps every bit except Write. |= adds bits, and the other options don't remove a specific flag reliably.
  4. 4. Why should members of a [Flags] enum be powers of two?

    With 1, 2, 4, 8 every combination sets a unique pattern of bits. Overlapping values make the combinations ambiguous.
  5. 5. What does Enum.TryParse<Season>("42", out var s) return?

    TryParse accepts numeric text and does not check whether the number is a declared member. Call Enum.IsDefined if only named members are valid.

Summary

  • An enum is a named set of integer constants; members count up from 0 unless you assign values, and the underlying type defaults to int.
  • Printing an enum shows the name; (int)x gives the number; default(MyEnum) is whatever has value 0, so keep a meaningful None or Unknown there.
  • Enum.TryParse, Enum.Parse, Enum.GetValues<T>(), Enum.GetNames<T>() and Enum.IsDefined handle text and enumeration. Parsing numeric text accepts undefined numbers.
  • Casting any integer to an enum succeeds, so validate outside data and end switches over enums with a _ arm that throws.
  • [Flags] enums use powers of two: combine with |, test with & or HasFlag, remove with & ~, toggle with ^.
  • Enums have no methods; put behavior in extension methods or helpers.

Next: Operators