Skip to Content
All posts

Enums in C#

2 min read ·  — #csharp-interview#junior#enums

Enums in C#

Enumerations, commonly known as enums, are a vital component in C# programming. An enumeration is a set of named integer constants, which allows you to define a type that consists of a finite set of distinct values. Enums are especially useful in enhancing the readability of the code by allowing the programmer to replace numbers or strings with meaningful symbolic names. They make the code more maintainable and less prone to errors.

Enums are often used to represent things like days of the week, months of a year, or different states in a process. They are a powerful tool in the programmer's toolkit that enhances the type safety of the code.

In this post, we will delve into the various aspects of enums in C#, including their declaration, usage, and advanced features. Whether you're preparing for a technical interview or simply looking to enhance your understanding of C#, this guide will equip you with the necessary knowledge about enums.

Declaring Enums

An enum is defined using the enum keyword, followed by the enum name and a body containing the named constants and their values. By default, the underlying type of the enumeration elements is int, and the first enumerator has the value 0.

Here's a simple example:

enum Days
{
    Sunday,    // 0
    Monday,    // 1
    Tuesday,   // 2
    Wednesday, // 3
    Thursday,  // 4
    Friday,    // 5
    Saturday   // 6
}

Using Enums

You can use an enum to define a variable, and assign a value to it:

Days today = Days.Wednesday;

Specifying Values

You can explicitly set the value for the constants in an enum:

enum Months
{
    January = 1,
    February = 2,
    // ...
    December = 12
}

Converting Between Enum and Other Types

C# allows you to convert between an enum and its underlying type, or even a string:

int dayNumber = (int)Days.Monday; // 1
string dayName = Days.Monday.ToString(); // "Monday"
Days day = (Days)Enum.Parse(typeof(Days), "Monday"); // Days.Monday

Flags Attribute

Enums can be used with the [Flags] attribute to represent a combination of values:

[Flags]
enum Permissions
{
    Read = 1,
    Write = 2,
    Execute = 4,
    FullControl = Read | Write | Execute
}

Permissions userPermissions = Permissions.Read | Permissions.Write;

Conclusion

Enums in C# offer a way to give meaningful names to sets of values, increasing the readability and maintainability of the code. Understanding how to use enums is a key skill for any C# developer and can be a vital part of a technical interview. By mastering the concepts detailed in this post, you will be well-prepared to handle questions and problems related to enums in your upcoming interview.

References