CodeBlanks Logo Icon CodeBlanks

Defining enums

Learn to define named constants with the enum keyword.

What is an enum?

An enum (enumeration) is a named set of constants. It groups related symbolic values under one roof, making code more readable and reducing the risk of sending the wrong value. Days of the week, months of the year, or order states are examples.

The declaration form is enum Color { Red, Green, Blue }. Here Color is a new type, while Red, Green and Blue are the values this type can take. By default each value maps to an integer, starting from zero.

Using an enum value

You can create a variable of your enum type and assign a value. The assignment uses the form EnumName.ValueName, combining the enum name and the member name with a dot. This way the value's type is explicit.

For example, Color favorite = Color.Green; assigns Green to favorite. Calling Console.WriteLine(favorite) prints Green. Type safety makes assigning the wrong type a compile error.

Default value

When an enum variable is declared without an assignment, its default value is 0. This corresponds to the enum's first member. That is why the first member is often chosen as "None" or "Default" to represent zero.

For example, after Color c; the value of c is 0; if Red is the first member, c becomes Red automatically. This behaviour also applies to class fields and properties.

Practice Define a Season enum

At the top of the file, define an enum called Season with members Spring, Summer, Autumn, Winter. In Main, assign Season.Summer to s as Season s = Season.Summer; and print it with Console.WriteLine.

Starter code

Program.cs
using System;

// Define the Season enum here

class Program
{
    static void Main()
    {
        // Assign Summer from Season and print it
    }
}

Sample solution

Program.cs
using System;

enum Season { Spring, Summer, Autumn, Winter }

class Program
{
    static void Main()
    {
        Season s = Season.Summer;
        Console.WriteLine(s);
    }
}

Expected output

Summer

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid enum declaration?

  • enum Color = Red, Green, Blue;
  • enum Color: Red Green Blue
  • Color enum { Red, Green, Blue }
  • enum Color { Red, Green, Blue } Correct answer

Explanation: Values go inside curly braces, separated by commas.

2 Assign the enum value

Question
Color c = ____;
Console.WriteLine(c);
Answer
Color c = Color.Red;
Console.WriteLine(c);

Explanation: Color.Red is how an enum value is assigned.

3 Match each concept with its description

Term Meaning
enum Color Color constants
Color.Red An enum value
default value first member (0)

All lessons in Beginner