C# Enum (Enumeration)
C# Enum (Enumeration)
Enum in C# is a special data type that allows you to define a set of named constants.
It improves code readability and maintains a collection of related constants.
Syntax
Basic Example
By default, enums start from 0. You can cast them to
int.
Assigning Custom Values
Using Enums in Switch
Enum with Different Underlying Type
You can specify the underlying type of enum:
Supported types: byte, sbyte, short, ushort, int, uint, long, ulong
Advantages of Enum
✔ Makes code more readable
✔ Prevents using magic numbers
✔ Helps maintain constants in one place
✔ Works with switch statements
Common Mistakes
❌ Assigning same value unintentionally
❌ Using enum as string directly without conversion
❌ Forgetting underlying type for large numbers
Summary
-
Enum = named constants
-
Default values start at 0, can assign custom values
-
Can specify underlying data type
-
Improves code readability and maintainability
