Enums (short for "enumerations") in C# are a value type that allows you to define a set of named integral constants. They provide a way to work with sets of related constants and improve code readability and maintainability. This tutorial covers the basics of enums, their use cases, how to define and use them, and best practices.
Enums are a special type that represents a group of related constants. Each enum type has an underlying integral type, which can be byte, sbyte, short, ushort, int, uint, long, or ulong. The default underlying type is int.
Example:
namespace EnumExamples;
// Define an enum
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Program
{
static void Main(string[] args)
{
DayOfWeek today = DayOfWeek.Monday;
Console.WriteLine($"Today is {today}"); // Output: Today is Monday
}
}
You define an enum using the enum keyword followed by the name of the enum and a set of named constants enclosed in curly braces. Each named constant in the enum has an associated integral value.
Example:
namespace EnumExamples;
// Define an enum with explicit values
enum ErrorCode
{
None = 0,
NotFound = 404,
ServerError = 500,
Unauthorized = 401
}
class Program
{
static void Main(string[] args)
{
ErrorCode error = ErrorCode.NotFound;
Console.WriteLine($"Error code: {(int)error}"); // Output: Error code: 404
}
}
Enums can be used to represent a set of related values in a type-safe way. You can assign enum values to variables, use them in switch statements, and compare them.
Example:
namespace EnumExamples;
// Define an enum
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Program
{
static void Main(string[] args)
{
DayOfWeek today = DayOfWeek.Wednesday;
// Use enum in a switch statement
switch (today)
{
case DayOfWeek.Sunday:
Console.WriteLine("Relax, it's Sunday!");
break;
case DayOfWeek.Monday:
Console.WriteLine("Back to work!");
break;
default:
Console.WriteLine($"Today is {today}");
break;
}
}
}
The Enum class provides several static methods and properties for working with enums, such as GetValues, GetNames, and IsDefined.
Example:
using System;
namespace EnumExamples;
// Define an enum
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Program
{
static void Main(string[] args)
{
// Get all enum values
DayOfWeek[] days = (DayOfWeek[])Enum.GetValues(typeof(DayOfWeek));
Console.WriteLine("Days of the week:");
foreach (DayOfWeek day in days)
{
Console.WriteLine(day);
}
// Get all enum names
string[] dayNames = Enum.GetNames(typeof(DayOfWeek));
Console.WriteLine("\nDay names:");
foreach (string name in dayNames)
{
Console.WriteLine(name);
}
// Check if a value is defined in the enum
bool isDefined = Enum.IsDefined(typeof(DayOfWeek), "Friday");
Console.WriteLine($"\nIs 'Friday' defined: {isDefined}");
}
}
Flags enums are a special kind of enum intended to be used as bit fields. You use the [Flags]
attribute to indicate that an enum can be treated as a bit field.
using System;
namespace EnumExamples;
// Define a flags enum
[Flags]
enum FileAccess
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
ReadWrite = Read | Write,
All = Read | Write | Execute
}
class Program
{
static void Main(string[] args)
{
FileAccess access = FileAccess.Read | FileAccess.Write;
// Check for specific flags
bool canRead = (access & FileAccess.Read) == FileAccess.Read;
bool canWrite = (access & FileAccess.Write) == FileAccess.Write;
bool canExecute = (access & FileAccess.Execute) == FileAccess.Execute;
Console.WriteLine($"Can Read: {canRead}"); // Output: Can Read: True
Console.WriteLine($"Can Write: {canWrite}"); // Output: Can Write: True
Console.WriteLine($"Can Execute: {canExecute}"); // Output: Can Execute: False
// Combine flags
access |= FileAccess.Execute;
Console.WriteLine($"New Access: {access}"); // Output: New Access: Read, Write, Execute
}
}
C# 9.0 introduced the Display
attribute, which allows you to define display names for enum values. This is particularly useful for displaying user-friendly names in UI elements.
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace EnumExamples;
// Define an enum with display names
enum Season
{
[Display(Name = "Winter Season")]
Winter,
[Display(Name = "Spring Season")]
Spring,
[Display(Name = "Summer Season")]
Summer,
[Display(Name = "Autumn Season")]
Autumn
}
class Program
{
static void Main(string[] args)
{
// Display enum names
foreach (Season season in Enum.GetValues(typeof(Season)))
{
Console.WriteLine($"Name: {season}, Display Name: {GetEnumDisplayName(season)}");
}
}
// Method to get the display name of an enum value
static string GetEnumDisplayName(Enum value)
{
return value.GetType()
.GetMember(value.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()?
.GetName() ?? value.ToString();
}
}
Enums in C# are a powerful feature that allows you to define and work with sets of related constants. By understanding how to define and use enums, as well as the benefits and best practices associated with their use, you can build more readable and maintainable applications.