Introduction
An enum helps you group related named values together. It makes your code easier to read and use.
An enum helps you group related named values together. It makes your code easier to read and use.
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.
enum Days
{
Sunday,
Monday,
Tuesday
}enum Colors { Red = 1, Green = 2, Blue = 4 }
enum Status { Pending, Approved = 5, Rejected }
This program declares an enum for traffic lights and prints the current light and its numeric value.
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}"); } }
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.
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.
enum in C#?Days with members Monday and Tuesday?enum Days { Monday, Tuesday };.enum Color { Red, Green, Blue };
Console.WriteLine((int)Color.Green);enum Status
{
Started = 1,
InProgress = 2,
Completed = "Done"
};Priority with members Low=1, Medium=5, and High=10 so that the values are not sequential?Pass the test and this pattern moves unknown