🔧 Casting to enum Doesn’t Validate Anything
C# lets you cast any integer to an enum type, valid member or not, with no error, no exception, no warning. That invalid value then silently flows through your switch statements, your business logic, and often all the way into your database.
🐞 The Problem
public enum OrderStatus { Pending = 0, Shipped = 1, Delivered = 2 }
int rawValue = 47; // came from a DB column, an API, deserialized JSON...
OrderStatus status = (OrderStatus)rawValue; // compiles, runs, no error
Console.WriteLine(status); // prints "47" - not a real OrderStatus at all
🔍 Why This Happens
Under the hood, a C# enum is just a named wrapper around an integer type. A cast is purely a compile-time type change - the runtime never checks whether the resulting value matches one of the enum's declared members. This is different from most other strongly-typed languages, and it's the single most common source of a "default: throw new Exception()" branch firing in production for a value nobody can explain.
✅ The Fix: Validate at the Boundary, Not in Every switch
- Check Enum.IsDefined() once, right where the raw value enters your system (deserialization, DB read, API input) — not scattered through business logic.
- Fail loudly and immediately (throw) rather than let an invalid value travel further into the app.
🛡️ Validate at the Boundary
int rawValue = 47;
if (!Enum.IsDefined(typeof(OrderStatus), rawValue))
{
throw new InvalidOperationException(
$"'{rawValue}' is not a valid OrderStatus.");
}
OrderStatus status = (OrderStatus)rawValue; // now guaranteed valid
⚠️ Even Better: TryParse for String Input
- If the raw value is a string (common with JSON/config), Enum.TryParse gives you validation and the cast in one safe call.
- Always add a default case to every switch on an enum anyway, even after validating at the boundary — defense in depth costs nothing.
An enum feels like a closed, safe set of values because the compiler treats it that way — but at runtime it’s just an int wearing a name tag, and nothing stops an invalid number from wearing it too.
