TExcelTAD
Home › C# › C# Enums

C# Enums

An enum (enumeration) is a type that defines a fixed set of named constants. Instead of passing around magic numbers or strings like 2 or "medium", you use readable, type-checked names like Priority.Medium. A typo becomes a compile error rather than a hidden bug.

Declaring and using an enum

csharp · try it yourself
using System;

Priority p = Priority.High;
Console.WriteLine(p);
Console.WriteLine(p == Priority.High);
Console.WriteLine((int)p);
Console.WriteLine((Priority)0);

enum Priority
{
    Low,
    Medium,
    High,
    Critical
}
High
True
2
Low

Each member is backed by an integer. By default the first is 0 and each following one is one higher. Printing an enum value shows its name; casting to int gives its number.

Choosing the underlying values

You can assign explicit values, which is useful when the numbers have meaning outside your program (HTTP codes, database values):

csharp · try it yourself
using System;

HttpStatus s = HttpStatus.NotFound;
Console.WriteLine(
quot;{s} = {(int)s}"); int code = 500; var fromCode = (HttpStatus)code; Console.WriteLine(fromCode); Console.WriteLine(Enum.IsDefined(typeof(HttpStatus), 418)); enum HttpStatus { Ok = 200, Created = 201, BadRequest = 400, NotFound = 404, ServerError = 500 }
NotFound = 404
ServerError
False

Note: Casting an arbitrary integer to an enum always succeeds, even if no member has that value — (HttpStatus)418 is legal and prints 418. Use Enum.IsDefined to validate numbers that come from outside.

Enums in switch

Enums and switch are a natural pair. The compiler even warns when a switch expression does not handle every possible value.

csharp · try it yourself
using System;

foreach (TrafficLight light in Enum.GetValues<TrafficLight>())
    Console.WriteLine(
quot;{light,-6} -> {Action(light)}"); static string Action(TrafficLight light) => light switch { TrafficLight.Red => "stop", TrafficLight.Yellow => "prepare to stop", TrafficLight.Green => "go", _ => throw new ArgumentOutOfRangeException(nameof(light)) }; enum TrafficLight { Red, Yellow, Green }
Red    -> stop
Yellow -> prepare to stop
Green  -> go

Enum.GetValues<T>() returns all members, which makes it easy to loop over them.

Parsing enums from text

Convert a string into an enum value with Enum.Parse or the safer Enum.TryParse:

csharp · try it yourself
using System;

string[] inputs = { "Tuesday", "friday", "Funday" };

foreach (string input in inputs)
{
    if (Enum.TryParse(input, ignoreCase: true, out DayOfWeek day))
        Console.WriteLine(
quot;{input} -> {day} ({(int)day})"); else Console.WriteLine(
quot;{input} -> not a day"); }
Tuesday -> Tuesday (2)
friday -> Friday (5)
Funday -> not a day

DayOfWeek is one of many enums built into .NET (others: ConsoleColor, StringComparison, FileMode).

Flags enums

When several options can be combined, give each member a distinct bit value (1, 2, 4, 8…) and mark the enum with [Flags]. Combine values with | and test them with HasFlag or &:

csharp · try it yourself
using System;

Permissions user = Permissions.Read | Permissions.Write;

Console.WriteLine(user);
Console.WriteLine(user.HasFlag(Permissions.Write));
Console.WriteLine(user.HasFlag(Permissions.Delete));

user |= Permissions.Delete;     // add a flag
user &= ~Permissions.Write;     // remove a flag
Console.WriteLine(user);
Console.WriteLine(Permissions.All);

[Flags]
enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4,
    All = Read | Write | Delete
}
Read, Write
True
False
Read, Delete
All

Summary

Task Code
Declare enum Size { Small, Medium, Large }
Use Size s = Size.Medium;
To number (int)s
From number (Size)2
To text s.ToString()
From text Enum.TryParse("Large", out Size s)
All values Enum.GetValues<Size>()

Tip: Name enums in the singular (Color, not Colors) unless they are [Flags] enums, which are conventionally plural (Permissions).

Test yourself

Given enum Level { Low, Mid, High }, what is (int)Level.High?

  1. 1
  2. 2
  3. 3
  4. "High"

Which attribute marks an enum whose values can be combined with |?

  1. [Combine]
  2. [Bits]
  3. [Flags]
  4. [Multiple]