|
| 1 | +Imagine working on a project to track order statuses, and you need to organize values like "Pending," "Shipped," or "Delivered" in a clear and manageable way. Using enums in C# lets you create a list of these order statuses. The use of enums makes it easier to use these statuses in your project without recreating or searching for them repeatedly. |
| 2 | + |
| 3 | +## Describe a scenario for enums and the value of enums |
| 4 | + |
| 5 | +Enums are ideal for representing a set of predefined values that are mutually exclusive or can be combined. For example, you might use an enum to define the seasons of the year: |
| 6 | + |
| 7 | +```csharp |
| 8 | +enum Season |
| 9 | +{ |
| 10 | + Spring, |
| 11 | + Summer, |
| 12 | + Autumn, |
| 13 | + Winter |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | +*Code sample demonstrates how to define an enum to represent mutually exclusive values.* |
| 18 | + |
| 19 | +Enums improve code readability by replacing numeric literals with meaningful names. They also help prevent invalid values from being assigned, as only the defined constants are allowed. |
| 20 | + |
| 21 | +> [!NOTE] |
| 22 | +> Enums can also represent combinations of choices using bit flags, which are useful for scenarios like file permissions or configuration options. |
| 23 | +
|
| 24 | +## Define enums |
| 25 | + |
| 26 | +To define an enum in C#, use the `enum` keyword followed by the name of the enum and its members. Here’s an example of a simple enum for the days of the week: |
| 27 | + |
| 28 | +```csharp |
| 29 | +enum DaysOfWeek |
| 30 | +{ |
| 31 | + Sunday, |
| 32 | + Monday, |
| 33 | + Tuesday, |
| 34 | + Wednesday, |
| 35 | + Thursday, |
| 36 | + Friday, |
| 37 | + Saturday |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +*Code sample demonstrates how to define an enum for the days of the week.* |
| 42 | + |
| 43 | +By default, the underlying type of an enum is `int`, and the values start at 0, incrementing by 1 for each member. |
| 44 | + |
| 45 | +> [!NOTE] |
| 46 | +> Enums are limited to integral types (for example, `int`, `byte`, `short`) and can't represent non-integral values like strings or decimals. |
| 47 | +
|
| 48 | +## Set underlying types and values for enums |
| 49 | + |
| 50 | +You can specify a different underlying integral type for an enum and assign custom values to its members. For example: |
| 51 | + |
| 52 | +```csharp |
| 53 | +enum ErrorCode : ushort |
| 54 | +{ |
| 55 | + None = 0, |
| 56 | + Unknown = 1, |
| 57 | + ConnectionLost = 100, |
| 58 | + OutlierReading = 200 |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +*Code sample demonstrates how to set a custom underlying type and values for an enum.* |
| 63 | + |
| 64 | +This flexibility allows you to align enum values with external systems or specific requirements. |
| 65 | + |
| 66 | +> [!TIP] |
| 67 | +> Avoid using non-integral types like `char` as the underlying type for enums, which can lead to unreliable behavior. |
| 68 | +
|
| 69 | +## Perform conversions with enums |
| 70 | + |
| 71 | +Enums support explicit conversions between their members and the underlying integral type. For example: |
| 72 | + |
| 73 | +```csharp |
| 74 | +DaysOfWeek day = (DaysOfWeek)3; |
| 75 | +Console.WriteLine(day); // Outputs: Wednesday |
| 76 | +``` |
| 77 | + |
| 78 | +*Code sample demonstrates how to perform an explicit conversion from an integral value to an enum.* |
| 79 | + |
| 80 | +You can validate enum values using the `System.Enum.IsDefined` method: |
| 81 | + |
| 82 | +```csharp |
| 83 | +bool isValid = Enum.IsDefined(typeof(DaysOfWeek), 3); |
| 84 | +Console.WriteLine(isValid); // Outputs: True |
| 85 | +``` |
| 86 | + |
| 87 | +*Code sample demonstrates how to validate an enum value using `System.Enum.IsDefined`.* |
| 88 | + |
| 89 | +> [!TIP] |
| 90 | +> If the value is invalid, you can handle it by assigning a default value or throwing an exception to ensure safe usage. |
| 91 | +
|
| 92 | +## Apply best practices for designing enums |
| 93 | + |
| 94 | +To design enums effectively: |
| 95 | + |
| 96 | +- Use singular nouns for simple enums and plural nouns for flag enums. |
| 97 | +- Provide a value of zero for simple enums, typically named `None`. |
| 98 | +- Avoid using special or reserved values, as they can confuse users. |
| 99 | +- Use powers of two for flag enums to enable bitwise operations. |
| 100 | + |
| 101 | +> [!TIP] |
| 102 | +> Consider adding extension methods to enums for more functionality, such as validation or formatting. |
| 103 | +
|
| 104 | +## Implement enums with custom values and methods |
| 105 | + |
| 106 | +While enums can't contain methods directly, you can add functionality using extension methods. For example: |
| 107 | + |
| 108 | +```csharp |
| 109 | +public static class DaysOfWeekExtensions |
| 110 | +{ |
| 111 | + public static bool IsWeekend(this DaysOfWeek day) |
| 112 | + { |
| 113 | + return day == DaysOfWeek.Saturday || day == DaysOfWeek.Sunday; |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +DaysOfWeek today = DaysOfWeek.Saturday; |
| 118 | +Console.WriteLine(today.IsWeekend()); // Outputs: True |
| 119 | +``` |
| 120 | + |
| 121 | +*Code sample demonstrates how to use an extension method to add functionality to an enum.* |
| 122 | + |
| 123 | +> [!TIP] |
| 124 | +> Use extension methods to enhance enums without modifying their definition, making them more versatile and reusable. |
| 125 | +
|
| 126 | +## Use object initializers with structs |
| 127 | + |
| 128 | +Define a struct with properties to group related data together and make it easier to initialize and work with instances of the struct. |
| 129 | + |
| 130 | +```csharp |
| 131 | +public struct Point |
| 132 | +{ |
| 133 | + public int X { get; set; } |
| 134 | + public int Y { get; set; } |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +Using an object initializer, you can create and initialize a `Point` instance like this: |
| 139 | + |
| 140 | +```csharp |
| 141 | +var point = new Point { X = 10, Y = 20 }; |
| 142 | +``` |
| 143 | + |
| 144 | +*Code sample demonstrates how to use an object initializer to set property values when creating a struct instance.* |
| 145 | + |
| 146 | +> [!NOTE] |
| 147 | +> Object initializers make your code more concise and easier to read, especially when working with structs that have multiple properties. |
| 148 | +
|
| 149 | +Enums in C# simplify code by allowing you to define a set of named constants, making it easier to represent and manage fixed values like statuses or categories while improving readability and maintainability. |
0 commit comments