0
0
C Sharp (C#)programming~5 mins

Enum declaration syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

An enum helps you group related named values together. It makes your code easier to read and use.

When you have a fixed set of related options, like days of the week.
When you want to replace numbers or strings with meaningful names.
When you want to limit possible values for a variable to a set list.
When you want to improve code clarity by using descriptive names.
When you want to avoid magic numbers or strings scattered in your code.
Syntax
C Sharp (C#)
enum EnumName
{
    Value1,
    Value2,
    Value3
}

Each value inside the enum is called a member.

By default, members start with 0 and increase by 1 automatically.

Examples
Simple enum for days of the week starting at 0.
C Sharp (C#)
enum Days
{
    Sunday,
    Monday,
    Tuesday
}
Enum with custom values assigned to each member.
C Sharp (C#)
enum Colors
{
    Red = 1,
    Green = 2,
    Blue = 4
}
Members after a custom value continue counting from that value.
C Sharp (C#)
enum Status
{
    Pending,
    Approved = 5,
    Rejected
}
Sample Program

This program declares an enum for traffic lights and prints the current light and its numeric value.

C Sharp (C#)
using System;

class Program
{
    enum TrafficLight
    {
        Red,
        Yellow,
        Green
    }

    static void Main()
    {
        TrafficLight light = TrafficLight.Yellow;
        Console.WriteLine($"Current light is: {light}");
        Console.WriteLine($"Numeric value: {(int)light}");
    }
}
OutputSuccess
Important Notes

You can cast enum members to int to get their numeric value.

Enums improve code readability and reduce errors from using raw numbers.

Enum members must be unique within the enum.

Summary

Enums group related named constants together.

Members have default numeric values starting at 0 unless assigned.

Use enums to make your code clearer and safer.