Introduction
Enums (short for "enumerations") in C# are a way to define a set of named integral constants. Enums are strongly typed constants that make your code more readable and maintainable. They are used to represent a collection of related values that can be associated with names, making the code easier to understand and less error-prone.
Defining an Enum
Enums are defined using the enum
keyword followed by the enum name and a list of named constants enclosed in curly braces. By default, the underlying type of the enum elements is int
, but you can specify a different integral type.
Syntax
enum EnumName
{
CONSTANT1,
CONSTANT2,
CONSTANT3
}
Example
enum DaysOfWeek
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
Using Enums
You can use enums to declare variables and assign them one of the predefined enum values. Enums can also be used in switch statements, comparisons, and other control structures.
Example
using System;
namespace EnumExample
{
class Program
{
enum DaysOfWeek
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
static void Main(string[] args)
{
DaysOfWeek today = DaysOfWeek.MONDAY;
Console.WriteLine($"Today is {today}");
Console.WriteLine($"Numeric value of {today} is {(int)today}");
// Using enums in a switch statement
switch (today)
{
case DaysOfWeek.SUNDAY:
case DaysOfWeek.SATURDAY:
Console.WriteLine("It's the weekend!");
break;
default:
Console.WriteLine("It's a weekday.");
break;
}
}
}
}
Output
Today is MONDAY
Numeric value of MONDAY is 1
It's a weekday.
Enum Underlying Type
By default, the underlying type of enum elements is int
, but you can specify a different integral type, such as byte
, sbyte
, short
, ushort
, uint
, long
, or ulong
.
Example
using System;
namespace EnumUnderlyingTypeExample
{
class Program
{
enum DaysOfWeek : byte
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
static void Main(string[] args)
{
DaysOfWeek today = DaysOfWeek.MONDAY;
Console.WriteLine($"Today is {today}");
Console.WriteLine($"Underlying numeric value of {today} is {(byte)today}");
}
}
}
Output
Today is MONDAY
Underlying numeric value of MONDAY is 1
Enum Methods
Enums come with several useful methods provided by the Enum
class in C#. These methods include Parse
, TryParse
, GetName
, GetNames
, GetValues
, and IsDefined
.
Example: Enum Methods
using System;
namespace EnumMethodsExample
{
class Program
{
enum DaysOfWeek
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
static void Main(string[] args)
{
// Get the name of the enum element
string dayName = Enum.GetName(typeof(DaysOfWeek), 1);
Console.WriteLine($"Enum name for 1: {dayName}");
// Get all names
string[] dayNames = Enum.GetNames(typeof(DaysOfWeek));
Console.WriteLine("Days of the week:");
foreach (string name in dayNames)
{
Console.WriteLine(name);
}
// Get all values
Array dayValues = Enum.GetValues(typeof(DaysOfWeek));
Console.WriteLine("Numeric values of days:");
foreach (int value in dayValues)
{
Console.WriteLine(value);
}
// Parse a string to an enum element
DaysOfWeek parsedDay = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), "FRIDAY");
Console.WriteLine($"Parsed day: {parsedDay}");
// TryParse a string to an enum element
if (Enum.TryParse("SATURDAY", out DaysOfWeek tryParsedDay))
{
Console.WriteLine($"TryParsed day: {tryParsedDay}");
}
else
{
Console.WriteLine("Failed to parse the day.");
}
// Check if a value is defined in the enum
bool isDefined = Enum.IsDefined(typeof(DaysOfWeek), "MONDAY");
Console.WriteLine($"Is 'MONDAY' defined in DaysOfWeek? {isDefined}");
}
}
}
Output
Enum name for 1: MONDAY
Days of the week:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Numeric values of days:
0
1
2
3
4
5
6
Parsed day: FRIDAY
TryParsed day: SATURDAY
Is 'MONDAY' defined in DaysOfWeek? True
Flags Enum
The Flags
attribute can be used to create an enum where each value represents a bit flag. This allows combining multiple values using bitwise operations.
Example
using System;
namespace FlagsEnumExample
{
[Flags]
enum FileAccess
{
READ = 1,
WRITE = 2,
EXECUTE = 4
}
class Program
{
static void Main(string[] args)
{
FileAccess access = FileAccess.READ | FileAccess.WRITE;
Console.WriteLine($"Access: {access}");
Console.WriteLine($"Can Read: {access.HasFlag(FileAccess.READ)}");
Console.WriteLine($"Can Write: {access.HasFlag(FileAccess.WRITE)}");
Console.WriteLine($"Can Execute: {access.HasFlag(FileAccess.EXECUTE)}");
// Adding EXECUTE access
access |= FileAccess.EXECUTE;
Console.WriteLine($"Updated Access: {access}");
}
}
}
Output
Access: READ, WRITE
Can Read: True
Can Write: True
Can Execute: False
Updated Access: READ, WRITE, EXECUTE
Conclusion
Enums in C# provide a way to define a set of named constants, making your code more readable and maintainable. By using enums, you can represent related values with meaningful names, reducing the likelihood of errors and making the code easier to understand. Enums also come with useful methods and can be combined using bitwise operations when marked with the Flags
attribute. Understanding and utilizing enums effectively can greatly improve the quality of your C# code.