C# Enums

Named constants for better code readability

🔢 What are Enums?

Enums (enumerations) are special value types that define a set of named constants. They make code more readable and maintainable by replacing magic numbers with meaningful names.


enum DaysOfWeek {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

// Usage
DaysOfWeek today = DaysOfWeek.Monday;
Console.WriteLine($"Today is {today}");
                                    

Output:

Today is Monday

Key Enum Concepts

📝

Named Constants

Meaningful names instead of numbers

enum Status {
    Active, Inactive
}
🔢

Integer Values

Each name has a numeric value

// Monday = 0
// Tuesday = 1
🎯

Custom Values

Assign specific numbers

enum Size {
    Small = 1,
    Large = 10
}
🔒

Type Safety

Prevents invalid values

Status s = 
    Status.Active;

🔹 Basic Enum Declaration

Enums (enumerations) define a set of named integral constants, making code more readable and less error‑prone. By default, the first member has a value of 0, with subsequent members incrementing by 1. For instance, a TrafficLight enum with Red, Yellow, Green provides meaningful names instead of magic numbers, enhancing code maintainability.

enum TrafficLight {
    Red,      // 0
    Yellow,   // 1
    Green     // 2
}

class Program {
    static void Main() {
        TrafficLight light = TrafficLight.Red;
        
        Console.WriteLine($"Light: {light}");
        Console.WriteLine($"Value: {(int)light}");
        
        if (light == TrafficLight.Red) {
            Console.WriteLine("Stop!");
        }
    }
}

Output:

Light: Red

Value: 0

Stop!

🔹 Enums with Custom Values

Enums can be assigned custom integer values, allowing alignment with external systems or meaningful numeric ranges. This is useful when you need to match existing codes—like priority levels where Critical = 20, High = 15, etc. Custom values preserve enum readability while supporting interoperability with databases, APIs, or legacy systems.

enum Priority {
    Low = 1,
    Medium = 5,
    High = 10,
    Critical = 20
}

class Task {
    public string Name;
    public Priority TaskPriority;
    
    public void ShowTask() {
        Console.WriteLine($"Task: {Name}");
        Console.WriteLine($"Priority: {TaskPriority} ({(int)TaskPriority})");
    }
}

// Usage
Task task = new Task {
    Name = "Fix bug",
    TaskPriority = Priority.Critical
};
task.ShowTask();

Output:

Task: Fix bug

Priority: Critical (20)

🔹 Enum in Switch Statements

Enums integrate seamlessly with switch statements, replacing ambiguous numeric literals with clear, named options. This improves code clarity and reduces bugs caused by incorrect integer values. For example, switching on a Weather enum (Sunny, Rainy, Cloudy) makes the logic self‑documenting and easier to extend compared to using raw integers.

enum Season {
    Spring,
    Summer,
    Fall,
    Winter
}

class Program {
    static void Main() {
        Season currentSeason = Season.Summer;
        
        switch (currentSeason) {
            case Season.Spring:
                Console.WriteLine("Flowers are blooming!");
                break;
            case Season.Summer:
                Console.WriteLine("It's hot and sunny!");
                break;
            case Season.Fall:
                Console.WriteLine("Leaves are falling!");
                break;
            case Season.Winter:
                Console.WriteLine("It's cold and snowy!");
                break;
        }
    }
}

Output:

It's hot and sunny!

🔹 Converting Enums

Enums in C# are strongly typed constants that improve code clarity and type safety. The Enum.Parse method converts a string representation to its corresponding enum value, such as converting "Delivered" to Status.Delivered. This is essential when reading external data like user inputs or configuration files. Using TryParse prevents exceptions by returning a boolean for invalid strings, ensuring robust and maintainable code in real-world applications.

enum OrderStatus {
    Pending,
    Processing,
    Shipped,
    Delivered
}

class Program {
    static void Main() {
        // Enum to int
        OrderStatus status = OrderStatus.Shipped;
        int statusValue = (int)status;
        Console.WriteLine($"Status value: {statusValue}");
        
        // Int to enum
        OrderStatus newStatus = (OrderStatus)3;
        Console.WriteLine($"New status: {newStatus}");
        
        // String to enum
        OrderStatus parsed = (OrderStatus)Enum.Parse(
            typeof(OrderStatus), "Processing");
        Console.WriteLine($"Parsed status: {parsed}");
    }
}

Output:

Status value: 2

New status: Delivered

Parsed status: Processing

🔹 Real-World Example

Interfaces enable dependency injection and loosely coupled architectures. In payment processing, an IPaymentGateway interface allows switching between CreditCardProcessor or PayPalProcessor without changing core logic. The system validates and processes payments through the interface, adhering to the Open/Closed Principle. This makes applications testable, maintainable, and adaptable to new payment methods.

enum PaymentMethod {
    CreditCard = 1,
    DebitCard = 2,
    PayPal = 3,
    Cash = 4
}

class Order {
    public double Amount;
    public PaymentMethod Payment;
    
    public void ProcessOrder() {
        Console.WriteLine($"Processing ${Amount} order");
        
        switch (Payment) {
            case PaymentMethod.CreditCard:
                Console.WriteLine("Charging credit card...");
                break;
            case PaymentMethod.PayPal:
                Console.WriteLine("Redirecting to PayPal...");
                break;
            case PaymentMethod.Cash:
                Console.WriteLine("Cash payment on delivery");
                break;
        }
        
        Console.WriteLine("Order completed!");
    }
}

// Usage
Order order = new Order {
    Amount = 99.99,
    Payment = PaymentMethod.PayPal
};
order.ProcessOrder();

Output:

Processing $99.99 order

Redirecting to PayPal...

Order completed!

🧠 Test Your Knowledge

What is the default value of the first enum member?