Home
Mastering C# Enums for Clean and Readable Code
In C#, an Enum (enumeration) is a distinct value type that enables a variable to be a set of predefined constants. By using the enum keyword, developers can create a named group of related constants, which significantly improves code readability by replacing "magic numbers" (anonymous literals) with descriptive names. At its core, every enum has an underlying integral type, such as int, byte, or long, which stores the actual value in memory.
Understanding the Fundamentals of C# Enums
The primary purpose of an enum is to define a category of options that are mutually exclusive. For instance, if you are tracking the state of an order, the order can be "Pending," "Shipped," or "Delivered." Instead of using integers like 0, 1, and 2, which can be confusing and error-prone, an enum provides a type-safe way to manage these states.
Basic Declaration and Default Values
To define an enum, you use the enum keyword. By default, the underlying type is int, and the numbering starts at zero.
-
Topic: Enums - C# language specification | Microsoft Learnhttps://learn.microsoft.com/th-th/dotNet/csharp/language-reference/language-specification/enums
-
Topic: docs/docs/csharp/language-reference/builtin-types/enum.md at main · dotnet/docs · GitHubhttps://github.com/dotnet/docs/blob/main/docs/csharp/language-reference/builtin-types/enum.md
-
Topic: docs/docs/csharp/fundamentals/types/enums.md at main · dotnet/docs · GitHubhttps://github.com/dotnet/docs/blob/main/docs/csharp/fundamentals/types/enums.md