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.
Exercise 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.
Show example solution
Define enum Season { Spring, Summer, Autumn, Winter }, then add Season s = Season.Summer; and Console.WriteLine(s);
Example solution:
using System;
enum Season { Spring, Summer, Autumn, Winter }
class Program
{
static void Main()
{
Season s = Season.Summer;
Console.WriteLine(s);
}
}
Test yourself
-
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
Show answer
enum Color { Red, Green, Blue } — Correct! Values go inside curly braces, separated by commas.
-
Assign the enum value
Color c = ____; Console.WriteLine(c);Show answer
Color c = Color.Red; Console.WriteLine(c); -
Match each concept with its description
- enum Color
- Color constants
- Color.Red
- An enum value
- default value
- first member (0)