Member-only story

Enum in C# with Example

Shahzad Aslam
2 min readMay 1, 2024

--

The enum is also called enumeration. It is a value type. Enum is used to define the set of named constant values.

Enum in C# with Example

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

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet