C#
Summary - Enums
Combine enum and Flags to write a permission check system.
Summary - Enums
In this group you learned enums. The enum keyword declares named constants; members start at 0 by default or take explicit values. With (int) you read the underlying value, and with (EnumName) you cast a number back to the enum.
Enum.Parse and Enum.TryParse parse a string into an enum; Enum.IsDefined checks validity. The [Flags] attribute enables bit field combinations, with | and HasFlag for combining and querying. In the next exercise you will combine these with a switch.
Enums and switch
Enum values work very well with the switch statement. Each case label represents an enum member, making the code easy to read and maintain. The compiler may warn when you do not cover all members; a default branch catches unexpected values.
For example, switch (status) { case Status.Active: ...; break; ... } shows the branching by state explicitly. Using an enum reduces the risk of wrong values and IDE autocomplete speeds you up.
Exercise Switch on the grade
Define an enum called Grade with members A, B, C, D, F. In Main, assign Grade.A to g as Grade g = Grade.A;. Then with switch (g), in the case Grade.A: branch print Console.WriteLine("Excellent"); and in the default branch print Console.WriteLine("Other");. Do not forget break.
Show example solution
Console.WriteLine("Excellent"); break; default: Console.WriteLine("Other"); break; }
Example solution:
using System;
enum Grade { A, B, C, D, F }
class Program
{
static void Main()
{
Grade g = Grade.A;
switch (g)
{
case Grade.A:
Console.WriteLine("Excellent");
break;
default:
Console.WriteLine("Other");
break;
}
}
}
Test yourself
-
Match each concept with its description
- enum
- Named constants
- (int)enumValue
- Gives the underlying value
- [Flags]
- Bit fields
- Enum.TryParse
- Safe parsing
-
Which is true for an enum?
enum Color { Red, Green, Blue }
- Its values are mutable
- It only takes strings
- Members can be added at runtime
- It is a named set of constants
Show answer
It is a named set of constants — Correct! An enum is a named set of constants.
Next lesson: try/catch