Enums
Learn how to define and use enums to represent a fixed set of named values in C#.
What is an Enum?
An enum (enumeration) defines a named set of related constants, making code far more readable than using raw numbers or strings to represent a fixed set of options.
Declaring an Enum
enum OrderStatus{ Pending, Shipped, Delivered, Cancelled}
OrderStatus status = OrderStatus.Shipped;Console.WriteLine(status);
if (status == OrderStatus.Shipped){ Console.WriteLine("Your order is on the way!");}Output
Click Run to see what this code prints.
Underlying Values
Behind the scenes, each enum member maps to an integer, starting at 0 by default — but you can assign your own values explicitly.
enum HttpStatus{ Ok = 200, NotFound = 404, ServerError = 500}
Console.WriteLine((int)HttpStatus.NotFound); // 404FAQs
Enums are checked at compile time, so a typo becomes a compile error instead of a silent runtime bug, and they're far cheaper to compare than strings.
Summary
- Enums represent a fixed, named set of related values.
- Each member maps to an underlying integer, customizable if needed.
- Enums are safer and more readable than raw numbers or strings.