- C# Fundamentals Tutorial
- C# - Intro
- C# - Installation
- C# - Basic Syntax
- C# - Variables
- C# - Data Types
- C# - Operators
- C# - Type Conversion
- C# - Arrays
- C# - Strings
- C# - Methods
- C# - Classes
- C# - If..Else
- C# - Loops
- C# - Enums
- C# - Inheritance
- C# - Encapsulation
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Regular Expressions
- C# - Exception Handling
C# - Enums
In C#, an enumeration (Enum) defines a set of named integral constants. Enums make code more readable and maintainable by giving friendly names to constant values.
To declare an Enum, use the ‘enum’ keyword followed by the name of the enum and the list of the values.
Enum Declaration
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
In above example ‘WeekDays’ is Enum name followed by the list of the values
You can also assign a predefined integer value like below:
enum WeekDays
{
1 = Monday,
2 = Tuesday,
3 = Wednesday,
4 = Thursday,
5 = Friday,
6 = Saturday,
7 = Sunday
}
Using Enum in Code
WeekDays today = WeekDays.Wednesday; // Declaring a variable of type WeekDays
Console.WriteLine(today);
// Output: Wednesday
// Using enums in switch statements
switch (today)
{
case WeekDays.Monday:
Console.WriteLine("It's Monday!");
break;
case WeekDays.Tuesday:
Console.WriteLine("It's Tuesday!");
break;
// ... other cases
default:
Console.WriteLine("It's not a weekday!");
break;
}
Enum Methods and Properties:
Enums offer various methods and properties that provide additional information or functionality:
- Enum.GetName(): Retrieves the name of the constant in the enum based on its value.
- Enum.GetValues(): Retrieves an array of the enum's values.
- Enum.Parse(): Converts a string representation of the enum to its corresponding value.
- Enum.IsDefined(): Checks if a specified value exists in the enum.