What is an enum in C#, and what are its pitfalls?
Quick Answer
An enum is a value type with a set of named integer constants — enum Status { Active, Suspended, Closed }. Pitfalls: the default value is 0 (whatever name maps to 0), you can cast any int to the enum type (invalid values slip through), and reordering members changes the numbers if a database stores them.
An enum is a named set of integer constants and it's a value type. The gotchas: the default value is zero, so whatever member is zero is what you get for an uninitialised variable — which is why I always define an explicit zero member like None. You can cast any integer to the enum type and the compiler won't stop you, so data from outside needs validating with Enum.IsDefined. And if I'm storing the enum in a database I either persist the name or pin the numeric values, because otherwise reordering the members quietly changes what stored rows mean.
- Always define an explicit
0member — oftenNoneorUnknown— so the default is meaningful. [Flags]+ power-of-two values allow bitwise combination (Permissions.Read | Permissions.Write).- Validate input from outside:
Enum.IsDefined(or pattern-match) — a cast from an int doesn't check. - Persisting: store the name (string) or fix the numbers explicitly, so a future reorder doesn't shift meanings.