ποΈ C# Enums β Define Named Constants with Strong Typing
π§² Introduction β Why Use Enums in C#?
When working with a set of related constant values, such as days of the week, user roles, or order statuses, plain integers or strings can lead to magic values and logic errors. Enums solve this by introducing named, strongly typed constants, enhancing readability, safety, and maintainability in your code.
π― In this guide, youβll learn:
- What enums are and how to declare them
- How to assign and convert enum values
- Use of flags and enum methods
- Real-world applications and best practices
π Core Concept β What is an Enum in C#?
An enum (enumeration) in C# is a value type that defines a set of named constants. By default, each name maps to an int starting from 0.
π£ Syntax β Enum Declaration
enum OrderStatus
{
Pending,
Processing,
Shipped,
Delivered,
Cancelled
}
π By default:
Pending = 0Processing = 1- and so on…
π» Code Example β Using Enums
OrderStatus status = OrderStatus.Shipped;
Console.WriteLine(status); // Output: Shipped
Console.WriteLine((int)status); // Output: 2
π§΅ Explanation:
- Enum improves readability over using
intvalues directly. - Casting reveals the underlying value.
π― Assigning Custom Values
enum HttpStatusCode
{
OK = 200,
NotFound = 404,
InternalServerError = 500
}
π Use Case: Align with external numeric systems like HTTP status codes.
π Enum to String and Vice Versa
OrderStatus status = (OrderStatus)Enum.Parse(typeof(OrderStatus), "Delivered");
Console.WriteLine(status); // Output: Delivered
π Convert strings to enums for deserialization, user input, etc.
π§© Flags Enum β Combine Multiple Values
[Flags]
enum FileAccess
{
Read = 1,
Write = 2,
Execute = 4
}
FileAccess permissions = FileAccess.Read | FileAccess.Write;
Console.WriteLine(permissions); // Output: Read, Write
π Use Case: Represent combinations of options using bitwise logic.
π Enum vs Const
| Feature | enum | const |
|---|---|---|
| Type-Safe | β Yes | β No |
| Grouped Constants | β Yes | β No |
| Default Type | int (modifiable) | Must define type |
| Use Case | Statuses, roles, categories | Individual literals |
π‘ Best Practices & Tips
π‘ Tip: Use [Flags] only when enum values will be combined using bitwise operators.
β οΈ Pitfall: Avoid using enums for dynamic or user-defined valuesβenums are static and defined at compile time.
π Best Practice: Use enums with switch or if blocks to simplify logic and avoid hardcoded values.
π οΈ Real-World Use Cases
- π§Ύ Order states:
Pending,Shipped,Delivered - πΌ User roles:
Admin,Manager,Employee - πΉοΈ Game states:
Paused,Running,GameOver - π File permissions:
Read,Write,Execute - π Status codes:
Success,Error,Timeout
π Summary β Recap & Next Steps
π§΅ Key Takeaways:
- Enums define a set of named integer constants.
- Improve code readability and eliminate “magic numbers”.
- Use
[Flags]for combinable enum values.
βοΈ Real-world relevance: C# enums are widely used for modeling states, roles, permissions, and more across web, desktop, and game apps.
β FAQ Section
β Can I assign custom values to enums?
β
Yes. Simply define them:
enum Level { Low = 1, Medium = 5, High = 10 }
β What is the default underlying type of enums in C#?
β
int. But you can change it to byte, short, long, etc.
β What is the use of the [Flags] attribute in enums?
β
Allows bitwise combination of enum values using | (OR), & (AND), etc.
β Can enums be nullable?
β
Yes:
OrderStatus? status = null;
β Can I use enums in switch statements?
β
Absolutely. Enums work perfectly with switch to replace if-else blocks.
Share Now :
