Member-only story
Enum in C# with Example
The enum is also called enumeration. It is a value type. Enum is used to define the set of named constant values.
Simple Enum
Here’s how you define and use an enum in C#:
Enum : Example
public enum FruitName
{
Apple,
Banana,
Mango,
Grape,
Orange,
Cherry,
Kiwi
}
Underlying Type:
By default, the underlying type of an enum is int. However, you can specify a different integral type (e.g., byte, short, long) explicitly if needed.
Example
public enum CustomEnum : byte
{
Value1,
Value2,
Value3,
}
Accessing Enum Values:
You can access the values of an enum using dot notation, like FruitName.Apple. These values are treated as named constants.
Example
FruitName.Apple
Enum Values as Integers:
While the enum values have symbolic names, they are represented as integers in memory. You can explicitly cast an enum value to its underlying type if needed.
Example
int fruitValue = (int)FruitName.Apple; // fruitValue will be 1