CHASH Tutorial



C# ENUMS


C# Enums (Enumerations)

An enum (short for enumeration) is a special "class" that represents a group of constants (unchangeable/read-only variables). Enums make code more readable and manageable.

💡 Use case:
Enums are ideal when you have a fixed set of related values, like days of the week, colors, or levels.

Syntax of Enum

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

Example: Using Enums in a Program

using System;

enum Level
{
    Low,
    Medium,
    High
}

class Program
{
    static void Main()
    {
        Level myLevel = Level.Medium;
        Console.WriteLine(myLevel);  // Output: Medium
    }
}
  

Enum Values as Numbers

By default, the first name has the value 0, the second 1, and so on.

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

class Program
{
    static void Main()
    {
        Console.WriteLine((int)Days.Tuesday); // Output: 2
    }
}
  

Assign Custom Values

You can assign custom numeric values to enum members.

enum ErrorCode
{
    None = 0,
    NotFound = 404,
    ServerError = 500,
    Forbidden = 403
}

class Program
{
    static void Main()
    {
        Console.WriteLine(ErrorCode.NotFound);        // Output: NotFound
        Console.WriteLine((int)ErrorCode.NotFound);   // Output: 404
    }
}
  
✔️ Enums make your code clean and type-safe.
They prevent invalid values from being used and help document allowed options clearly.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review