๐ŸŽ“ A1Learner
๐Ÿ”

C# Enums

An enum is a type that holds a fixed set of named values. Each name stands for one choice from that set.

Print an Enum Value

The enum Level lists three names. Main saves one value and prints it.

using System;

enum Level
{
    Low,
    Medium,
    High = 3
}

class Program
{
    static void Main(string[] args)
    {
        Level level = Level.Medium;
        Console.WriteLine(level);
    }
}

Read the Numbers

A cast to int shows the number behind a name. Medium is the second name, so its number is 1.

using System;

enum Level
{
    Low,
    Medium,
    High = 3
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine((int)Level.Medium);
        Console.WriteLine((int)Level.High);
    }
}

Switch on an Enum

A switch tests the saved value against enum names. The High case matches here.

using System;

enum Level
{
    Low,
    Medium,
    High = 3
}

class Program
{
    static void Main(string[] args)
    {
        Level level = Level.High;
        switch (level)
        {
            case Level.Low:
                Console.WriteLine("Low level.");
                break;
            case Level.Medium:
                Console.WriteLine("Medium level.");
                break;
            case Level.High:
                Console.WriteLine("High level.");
                break;
        }
    }
}

Example

using System;

enum Day
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

class Program
{
    static void Main(string[] args)
    {
        Day today = Day.Friday;
        switch (today)
        {
            case Day.Monday:
                Console.WriteLine("Start of the week.");
                break;
            case Day.Friday:
                Console.WriteLine("Almost weekend.");
                break;
            default:
                Console.WriteLine("Midweek day.");
                break;
        }
    }
}

Key points

  • Enum: a type declared with the enum keyword and a list of names.
  • Write an enum value with the type name, a dot, and the name.
  • Enum names print as text when a value is printed.
  • The first name has the number 0 by default, and each next name counts up by one.
  • A name can be given its own number with an equals sign.
  • Cast an enum value to int to read its number.
  • A switch can test an enum value case by case.

In this example, the enum Day lists the seven days of the week. Main saves Day.Friday in the variable today. The switch tests today against its cases in order. The Monday case does not match. The Friday case matches, so its line prints. The default case is skipped.

Note

Enum names are fixed at declaration. New names cannot be added while the program runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does (int)Level.Medium print when Medium is the second name in the enum?