C#
Enum constants
Learn to define grouped constants with enum.
Enum constants
An enum is a set of named constants that groups related values in a type-safe way. Declaration: enum Status { Pending, Active, Done }.
Enum values are int by default starting from zero: Pending = 0, Active = 1, Done = 2. Values can be assigned: enum Level { Low = 1, Mid = 5, High = 10 }. An enum prevents numeric constants from mixing; Status.Active and Level.Mid are different types and cannot be confused.
Using enums
Enum values are assigned as Status current = Status.Active;. The numeric form is obtained with (int)current. Console.WriteLine(current) prints the enum name (Active).
You can convert a string to an enum value with Enum.Parse<Status>("Active"). The Flags attribute enables bitwise operations: [Flags] enum Perms { Read = 1, Write = 2, Exec = 4 }. This lesson focuses on basic enum usage.
Exercise Status enum
Define an enum Status with members Pending, Active, Done. In Main, assign Status current = Status.Active;, then print current and (int)current.
Show example solution
Add `enum Status { Pending, Active, Done }` to the file. In Main write `Status current = Status.Active; Console.WriteLine(current); Console.WriteLine((int)current);`.
Example solution:
using System;
enum Status
{
Pending,
Active,
Done
}
class Program
{
static void Main()
{
Status current = Status.Active;
Console.WriteLine(current);
Console.WriteLine((int)current);
}
}
Test yourself
-
Fill in the blank: enum declaration
enum Status
{
Pending,
Active,
____
}
Show answer
enum Status
{
Pending,
Active,
Done
}
-
Match: enum properties
- underlying type
- int (default)
- first value
- 0
- type safety
- different enums don't mix
- member access
- Status.Active
-
Which statement about enums is correct?
- Enum values are stored as strings.
- Adding a new enum value causes a compile error.
- An enum is a set of named constants and is type safe.
- An enum can only contain one value.
Show answer
An enum is a set of named constants and is type safe. — Correct. An enum is a set of named constants and groups them in a type-safe way.
Next lesson: Summary - Class constants