Glossary / Enums

Enums

An enum defines a set of named constants backed by an integral type, usually representing a closed set of modes, states, or options. Enums improve readability over magic numbers, but their underlying numeric values, serialization, and flag semantics need deliberate design when they form public or persisted contracts.

Values and representations

public enum Status : byte { Pending = 1, Active = 2, Closed = 3 }

The default underlying type is int; another integral type can be specified. Members are compile-time constants and default to incrementing values unless assigned. An enum variable can hold any value representable by its underlying type, including unnamed values through casts or external data, so validate inputs rather than assuming every value is a declared member.

[Flags] marks an enum intended for bitwise combinations; assign distinct power-of-two values and use bitwise operators. Enum.HasFlag is readable but may box in some usage/runtime contexts; direct bitwise tests can be clearer and avoid allocations. Do not use [Flags] for mutually exclusive alternatives.

Compatibility and serialization

Changing numeric values can break persisted data, protocols, and interop. Avoid using enum ordinal positions as stable IDs. JSON serializers may represent enums as numbers or strings depending on configuration; string conversion improves readability but renaming values can also break consumers. Unknown values should be handled intentionally for forward compatibility.

Interview questions

  1. Can an enum contain an undeclared value? Yes; casts and external data can supply any underlying numeric value.
  2. What makes a flags enum valid? Distinct bit values, typically powers of two, for combinable options.
  3. Why explicitly assign public enum values? To prevent reorder/insert changes from altering persisted numeric contracts.
  4. Does [Flags] enforce bit values? No; it is descriptive metadata/convention.
  5. How handle unknown serialized values? Validate, preserve, map to an unknown case, or reject according to contract.

References