C# ยท Chapter 38 of 46

C# Enums

An enum (enumeration) is a special type that represents a fixed set of named constants, making code more readable than using plain numbers. For example, an enum could represent days of the week or order statuses.

By default, enum values are backed by integers starting at 0, but you can assign specific values explicitly if needed.

Syntax
enum Name {
  Value1, Value2, Value3
}

Defining and using enums

An enum is declared with the `enum` keyword and a list of named values, like `enum Day { Monday, Tuesday, Wednesday }`. You access a value using the enum name and a dot, like `Day.Monday`.

Underlying values

Each enum member has an underlying int value, starting at 0 by default. You can cast between an enum and its int value, and assign custom starting values explicitly.

Example 1 (csharp)
using System;

enum Day { Monday, Tuesday, Wednesday }

class Program {
  static void Main() {
    Day today = Day.Tuesday;
    Console.WriteLine(today);
  }
}
Output
Tuesday

today stores an enum value, which prints as its named label rather than a number.

Example 2 (csharp)
using System;

enum Day { Monday, Tuesday, Wednesday }

class Program {
  static void Main() {
    Day today = Day.Wednesday;
    int value = (int)today;
    Console.WriteLine(value);
  }
}
Output
2

Casting an enum to int reveals its underlying numeric value, starting at 0 by default.

Key points

  • An enum defines a fixed set of named constant values.
  • Enum values are backed by integers, starting at 0 by default.
  • Enums make code more readable than using raw numbers.
  • You can cast between an enum and its underlying int type.
๐Ÿ’ก Note: Use enums instead of 'magic numbers' whenever a variable can only take a small, fixed set of meaningful values.

๐Ÿ“ Quick Quiz

1. What does an enum represent?

2. What is the default underlying type of an enum's values?

3. What does the first value in an enum default to?