Enums help us give names to a set of related values. This makes code easier to read and less error-prone.
When you have a fixed list of options, like days of the week.
When you want to make your code clearer by using names instead of numbers.
When you want to avoid mistakes from using wrong values.
When you want to group related constants together.
When you want to improve code maintainability and readability.
Syntax
C Sharp (C#)
enum EnumName
{
Value1,
Value2,
Value3
}
Each name inside the enum represents a constant value.
By default, the first value is 0, the next is 1, and so on, but you can set specific numbers if needed.
Examples
This enum lists some days of the week.
C Sharp (C#)
enum Days
{
Sunday,
Monday,
Tuesday
}
This enum assigns specific numbers to each traffic light color.
C Sharp (C#)
enum TrafficLight
{
Red = 1,
Yellow = 2,
Green = 3
}
Sample Program
This program uses an enum to represent days. It prints the current day and a message if it's Monday.
C Sharp (C#)
using System;
class Program
{
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
staticvoid Main()
{
Days today = Days.Monday;
Console.WriteLine($"Today is: {today}");
if (today == Days.Monday)
{
Console.WriteLine("Start of the work week!");
}
}
}
OutputSuccess
Important Notes
Enums improve code clarity by replacing magic numbers with meaningful names.
Using enums helps prevent invalid values because only defined names can be used.
Summary
Enums group related named constants together.
They make code easier to read and maintain.
Enums help avoid errors from using wrong or unclear values.
Practice
(1/5)
1. Why do we use enum types in C#?
easy
A. To create variables that can hold any data type
B. To group related named constants for better code clarity
C. To perform mathematical calculations faster
D. To store large amounts of text data efficiently
Solution
Step 1: Understand the purpose of enums
Enums group related named constants, making code easier to read and maintain.
Step 2: Compare other options
Other options describe unrelated uses like variable types or data storage, which enums do not do.
Final Answer:
To group related named constants for better code clarity -> Option B
Quick Check:
Enums = group named constants [OK]
Hint: Enums group related names, not data or calculations [OK]
Common Mistakes:
Thinking enums store any data type
Confusing enums with variables or arrays
Assuming enums improve performance directly
2. Which of the following is the correct way to declare an enum in C#?
easy
A. enum Colors = (Red, Green, Blue);
B. enum Colors { 'Red', 'Green', 'Blue' };
C. enum Colors: Red, Green, Blue;
D. enum Colors { Red, Green, Blue };
Solution
Step 1: Recall enum declaration syntax
In C#, enums are declared with enum Name { Value1, Value2, ... } syntax.
Step 2: Check each option
enum Colors { Red, Green, Blue }; matches correct syntax; others use invalid symbols or punctuation.