8️⃣ C# Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 39 views

πŸ—οΈ 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 = 0
  • Processing = 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 int values 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

Featureenumconst
Type-Safeβœ… Yes❌ No
Grouped Constantsβœ… Yes❌ No
Default Typeint (modifiable)Must define type
Use CaseStatuses, roles, categoriesIndividual 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ—οΈ C# Enums

Or Copy Link

CONTENTS
Scroll to Top