C# Enums

C# Enums

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables). The word enum stands for "enumerations", which means "specifically listed".

Enums are typically used when you have values that you know aren't going to change, like months, days of the week, colors, or difficulty levels in a game.


Creating an Enum

To create an enum, use the enum keyword instead of class or interface, and separate the enum items with a comma.

By default, the first item of an enum has the value 0. The second has the value 1, and so on.

Example: Using Enums

using System;

class Program { // Define the enum enum Level { Low, // 0 Medium, // 1 High // 2 }

static void Main(string[] args) { // Accessing an enum item using dot syntax Level myVar = Level.Medium; Console.WriteLine(myVar); // Outputs "Medium" } }


Enum Values

As mentioned, enums have integer values assigned to them behind the scenes. You can explicitly assign your own values if you prefer, and the subsequent items will update accordingly.

Example: Enum Integer Values

using System;

class Program { enum Months { January = 1, // 1 February, // 2 (automatically follows 1) March, // 3 April // 4 }

static void Main(string[] args) { // You can cast an enum to an integer to get its numeric value int myNum = (int)Months.April; Console.WriteLine("April is month number: " + myNum); } }

Why And When To Use Enums?

Use enums when you have values that you know aren't going to change. Enums reduce bugs in your code by limiting the options a variable can take.

For instance, if a method expects a Level enum, a programmer can only pass Level.Low, Level.Medium, or Level.High. They can't accidentally pass a string like "SuperHigh", which would cause an error!

Note: Enums can be created inside a class or directly inside a namespace.


Exercise

?

By default, what is the underlying integer value of the first item in an enum?