Enums & [Flags]
Define enums with explicit values and underlying types, convert and parse safely, and model combinable options with [Flags].
Enums overview
Goal: Use enums for named constants and [Flags] for combinable options.
- Names map to numbers
- Underlying type (int by default)
- Cast, parse, and validate
- Bitwise combine with [Flags]
Basic enum
Enums are named constants. You can print the name or cast to the underlying number.
using System;
public enum OrderStatus
{
Pending = 0,
Processing = 1,
Shipped = 2,
Delivered = 3,
Cancelled = 4
}
public class Program
{
public static void Main(string[] args)
{
OrderStatus s = OrderStatus.Processing;
Console.WriteLine("Status = " + s);
Console.WriteLine("Numeric = " + (int)s);
}
}