C# - enum or enumeration
An enum or enumeration in C# is a special "value type" that lets you specify a group of named numeric constants. It can make your code more readable and understandable by replacing numbers with meaningful names. Enums are defined using the enum keyword and provide an efficient way to assign symbolic names to integral values, typically used to represent a list of possible states or options.
In C#, you create an enum by writing the keyword enum, then giving it a name, and listing out all the options it can have inside curly brackets {}.. Here's the general syntax:
enum EnumName
{
Value1,
Value2,
Value3,
// ...
}
In an enum, every option is automatically given a number, beginning with 0 for the first option and going up by 1 for each one after that. If you want, you can also choose specific numbers for each option yourself. Let's look at an example:
enum DayOfWeek
{
Monday=1,
Tuesday=2,
Wednesday=3,
Thursday=4,
Friday=5,
Saturday=6,
Sunday=7
}
In the given example, there's an enum called DayOfWeek
that stands for the days of the week. Each day is given a number that starts at '1' for Monday
and goes up to '7' for Sunday
.
Here's a simple example to illustrate the use of enums in C#. Let's say we have a console application that tracks the status of a customer support ticket:
using System;
public class Program
{
// Define the enum for ticket status
enum TicketStatus
{
Open,
InProgress,
Resolved,
Closed
}
static void Main()
{
// Create a variable of type TicketStatus
TicketStatus ticket = TicketStatus.Open;
// Output the initial status of the ticket
Console.WriteLine("The ticket status is: " + ticket);
// Update the status of the ticket
ticket = TicketStatus.Resolved;
// Output the updated status of the ticket
Console.WriteLine("The ticket status is now: " + ticket);
}
}
When you run this code, the output will be:
The ticket status is: Open
The ticket status is now: Resolved
In the example above, we've defined an enum
named TicketStatus
with four possible values that represent the status of a customer support ticket: Open
, InProgress
, Resolved
, and Closed
. These names are much clearer than using numbers like 0, 1, 2, or 3, and they help anyone reading the code understand what the values represent without needing additional explanation.
The ticket
variable is declared with the TicketStatus
enum type and initially set to TicketStatus.Open
. We print its value, change it to TicketStatus.Resolved
, and print the updated value. The console output shows the names of the enum members, which correspond to the underlying integer values of the enum. By default, the associated numeric values start at 0 and increase by 1, but you can assign any integer values to the names explicitly if needed. Enums in C# help to enforce type safety and can make your code more maintainable.