Page Content

Tutorials

C# Enumerations (Enums) Important Features and Declarations

C# Enumerations (Enums)

The C# language’s enums, which stand for enumerations, are essential for defining a collection of named integral constants. User-defined value types are the category for them. The basic goal of enums is to replace “magic numbers” with meaningful identifiers, which makes code easier to understand and manipulate.

Enums in C# are explained in full here, along with code examples:

Important Features and Declarations

Value Type: As C# value types, enums don’t retain memory addresses like reference types do; instead, they contain their contents directly. They have their roots in System.ValueType.

Underlying Numeric Type: By default, an enum’s integral type is int. Nevertheless, any other integral numeric type, including byte, sbyte, short, ushort, uint, long, or ulong, can be specifically specified as the underlying type. The values given to enum members have to fall inside the specified base type’s range.

Named Constants: In essence, enum members are named integer constants. By default, the first member is set to 0 if no explicit values are specified, and each member increases by one. Enum members can have explicit integer values assigned to them.

Declaration Syntax

To declare an enum, use the enum keyword, then the block with its members and the enum’s name.

// Basic Enum Declaration (default int type, values start from 0)
public enum Season
{
    Spring,  // 0
    Summer,  // 1
    Autumn,  // 2
    Winter   // 3
} 
// Enum with explicit underlying type and assigned values
public enum CoffeeSize : byte
{
    Small = 100,
    Normal = 150,
    Double = 300
} 
// Enum where values are implicitly set based on previous explicit assignments
enum Alphabet
{
    A,      // 0 (default)
    B = 5,  // 5
    C,      // 6 (B + 1)
    D = 20, // 20
    E       // 21 (D + 1)
} 

Naming Conventions: Most enums (like Volume) should be named in the single, but enums that function as bit fields should be named in the plural. Don’t repeat the enum name among its members or start it with “enum” as a suffix.

Default Value: In the event that no member is explicitly assigned a value, the enum variable’s default value is 0. Defining a None or Default member with a value of 0 is a recommended practice to prevent confusion.

Usage of Enums

Declaring and Assigning Variables: Declaring variables of the enum type and giving them a named constant are both possible.

Conversion Between Enum and Integer: To obtain its numerical value, you can cast an enum member to its underlying integer type. You can also cast an integer back to an enum type.

String Conversion:

String to Enum: Put Enum or the ToString() function to use.ReturnName(). Enum should be used.You can use Enum or TryParse() for safe conversion, which returns a boolean indicating success.If the string doesn’t match a member, Parse() would raise an ArgumentException.

Iterating Enum Members: Using Enum, you may obtain a string array containing all member names.Enum or GetNames() for all member values.Use GetValues().

switch-case Statements: Enums are frequently used in switch-case statements because they provide conditional logic based on enum values that is both type-safe and understandable.

Advanced Features and Considerations

FlagsAttribute for Bit Fields: Use the [Flags] property when an enum has a group of flags that can be joined using bitwise operations (like permissions). The behaviour of ToString() is altered by this attribute to list all combined enum members. Bitwise operations require that members be powers of two or combinations of them. It is common practice to utilise the left-shift operator () for cleaner definitions.

DescriptionAttribute: An enum member can have a human-readable description attached to it using the [System.ComponentModel.Description] attribute. In user interfaces, this is helpful for presenting enum values.

Unexpected Values: Integers support enums, therefore if an enum variable is explicitly converted from an integer, it may include an integer value that doesn’t match any declared enum member. If an enum value is a genuine, defined member, you can verify it using Enum.IsDefined().

Encapsulation: Declaring enums inside classes allows for better encapsulation since it logically groups the enum with the class to which it belongs.

In the.NET Framework, enums are used extensively. For example, they are used to define string comparison choices (StringComparison) and file access modes (FileMode, FileAccess, FileShare).

Code Examples

Here are code examples demonstrating the declaration and usage of enums in C#:

using System; // Required for Console operations 
public class WorkingEnumExample
{
    // Basic Enum Declaration
    // By default, the underlying type is 'int', and values start from 0 and increment by 1.
    public enum DayOfWeek
    {
        Sunday,    // implicitly 0
        Monday,    // implicitly 1
        Tuesday,   // implicitly 2
        Wednesday, // implicitly 3
        Thursday,  // implicitly 4
        Friday,    // implicitly 5
        Saturday   // implicitly 6
    }
    // Enum with Explicit Assigned Values and a Custom Underlying Type
    // You can explicitly set the underlying integral type, such as 'byte'.
    public enum TrafficLightColor : byte
    {
        Red = 1,
        Yellow = 2,
        Green = 3
    }
    // Enum with a Mix of Default and Explicit Values
    public enum StatusCode
    {
        Success = 200,          // explicitly 200
        BadRequest = 400,       // explicitly 400
        Unauthorized,           // implicitly 401 (increments from BadRequest + 1) 
        NotFound = 404,         // explicitly 404
        ServerError = 500       // explicitly 500
    }
    public static void Main(string[] args)
    {
        Console.WriteLine("--- Enum Declaration and Basic Usage ---"); 
        // 1. Declaring a variable of an enum type and assigning a named constant 
        DayOfWeek today = DayOfWeek.Wednesday;
        Console.WriteLine($"Today is: {today}"); // Output: Today is: Wednesday 
        // 2. Accessing the underlying integer value of an enum member
        // The compiler automatically assigns integer digits to enum constants.
        int dayValue = (int)today;
        Console.WriteLine($"Numeric value of {today}: {dayValue}"); 
        // 3. Converting an integer value back to an enum type 
        DayOfWeek weekendDay = (DayOfWeek)6; // Example of casting an integer to an enum type 
        Console.WriteLine($"Day with numeric value 6: {weekendDay}"); 
        // Demonstrating an enum with explicit values and custom underlying type
        TrafficLightColor myColor = TrafficLightColor.Green;
        Console.WriteLine($"Current Traffic Light Color: {myColor} (Numeric: {(byte)myColor})"); // Output: Current Traffic Light Color: Green (Numeric: 3)
    }
}

Output

--- Enum Declaration and Basic Usage ---
Today is: Wednesday
Numeric value of Wednesday: 3
Day with numeric value 6: Saturday
Current Traffic Light Color: Green (Numeric: 3)

You can also read Object Class In C#: The Foundation Of the Type System

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index