An enum (short for “enumeration”) in C# is a special value type that allows you to define a set of named constants.
Enums are often used to represent a collection of related values, such as days of the week, months of the year, error codes, etc. Instead of using numbers or strings directly in your code, you can use an enum to make your code more readable and easier to maintain.
Characteristic of Enum
1. Underlying Type: By default, the underlying type of an enum is int, and the values are represented as integers starting from 0. However, you can specify a different underlying type (e.g., byte, short, etc.).
2. Named Constants: Each item in an enum represents a constant value, which can be assigned to a variable.
3. Strong Typing: Enums give you strong typing, meaning you cannot assign a value outside the defined range of the enum.
Syntax:
enum EnumName
{
Constant1 = Value1,
Constant2 = Value2,
// ...
}
Explanation:
1. EnumName is the name of the enum.
2. Constant1, Constant2 are the enum values (also known as members).
3. Value1, Value2 are the numeric values associated with each constant (optional). If not provided, the first value is 0, and each subsequent value is incremented by 1.
Example:
using System;
enum Days
{
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
class Program
{
static void Main()
{
Days tuesday = Days.Tuesday;
Console.WriteLine($"Today is: {tuesday}"); // Outputs: Today is: Tuesday
Console.WriteLine($"Numeric value of today is {tuesday}"); // Outputs: Numeric value of today is Tuesday
}
}
Output:
Numeric value of today is Tuesday
Explanation:
We define an enum Days with days of the week. By default, the first member (Sunday) has a value of 0, and each subsequent member’s value is automatically incremented by 1.
Example:
using System;
enum StatusCode
{
OK = 200, // Custom value
NotFound = 404, // Custom value
InternalServerError = 500, // Custom value
}
class Program
{
static void Main()
{
StatusCode ok_status = StatusCode.OK;
StatusCode notfound_status = StatusCode.NotFound;
Console.WriteLine($"Status: {ok_status}"); // Outputs: Status: OK
Console.WriteLine($"Numeric value: {(int)ok_status}"); // Outputs: Numeric value: 200
Console.WriteLine($"Status: {notfound_status}"); // Outputs: Status: NotFound
Console.WriteLine($"Numeric value: {(int)notfound_status}"); // Outputs: Numeric value: 404
}
}
Output:
Numeric value: 200
Status: NotFound
Numeric value: 404