Casting int to enum in C#: 5 Fatal Errors and How to Avoid Them

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Casting int to enum in C#: Why It Breaks Code and How to Fix It Properly

\n\n

Every C# developer, even with just a couple of months of experience, eventually faces the question: «How do I cast int to enum in C#?». This query on Stack Overflow has gathered hundreds of thousands of views — and for good reason. It seems simple enough: write (MyEnum)myInt and you're done. But the devil, as always, is in the details. Incorrectly casting int to enum can lead to exceptions, hard-to-find bugs, and even production server crashes.

\n\n

In this article, we'll break down the top 5 mistakes when casting int to enum, show working C# examples, and provide a clear algorithm for safe conversion. If you write in C# and use enumerations, this information will save you hours of debugging.

\n\n

Mistake #1: Naive Casting Without Validation — «What if the number is invalid?»

\n\n

The most common method beginners find online is a direct cast:

\n\n
enum Status\n{\n    Active = 1,\n    Inactive = 2,\n    Pending = 3\n}\n\nint input = 5; // User sent something wrong\nStatus status = (Status)input; // No error, but status == (Status)5\nConsole.WriteLine(status); // Output: 5 — garbage value!\n
\n\n

The code will compile and run without an exception. But the variable status now contains the value 5, which is not in the Status enum. In C#, enumerations are essentially integers with names. The compiler does not check whether the value belongs to the set of constants. This is a classic trap: casting int to enum technically works, but logically, it's a bug.

\n\n

How to avoid: always use the Enum.IsDefined() method before casting.

\n\n
if (Enum.IsDefined(typeof(Status), input))\n{\n    Status status = (Status)input;\n}\nelse\n{\n    // Error handling: logging, default value, or exception\n    Console.WriteLine($"Invalid value {input} for Status");\n}\n
\n\n

Remember: Enum.IsDefined() is slow for frequent calls, but for one-off operations, it's an ideal safeguard.

\n\n

Mistake #2: Ignoring Flag Enumerations ([Flags])

\n\n

When working with enumerations marked with the [Flags] attribute, the validation logic changes. Enum.IsDefined() will return false for combinations of flags, even if they are valid.

\n\n
[Flags]\nenum Permissions\n{\n    None = 0,\n    Read = 1,\n    Write = 2,\n    Execute = 4\n}\n\nint input = 3; // Read + Write\nif (Enum.IsDefined(typeof(Permissions), input))\n{\n    // This won't execute! 3 is not a single constant\n}\n
\n\n

For flags, you need a different check: whether all bits in the number correspond to defined values.

\n\n
bool IsValidFlags<T>(int value) where T : Enum\n{\n    int allValues = 0;\n    foreach (var v in Enum.GetValues<T>())\n    {\n        allValues |= Convert.ToInt32(v);\n    }\n    return (value & ~allValues) == 0;\n}\n\nif (IsValidFlags<Permissions>(input))\n{\n    Permissions perms = (Permissions)input; // Safe\n}\n
\n\n

Or, more simply, use the built-in Enum.IsDefined() check for each individual flag if there are only a few.

\n\n

Mistake #3: Forgetting About Negative Numbers and Overflow

\n\n

An enum in C# is based on int by default, but it can be byte, short, long, etc. If you cast an int to an enum whose underlying type is byte, you risk getting an overflow exception or, worse, a silent value distortion.

\n\n
enum SmallEnum : byte\n{\n    A = 0,\n    B = 255\n}\n\nint bigValue = 300;\nSmallEnum se = (SmallEnum)bigValue; // Compilation error? No!\n// But the value will be truncated: se == (SmallEnum)44 (300 % 256)\n

                
                

Blogs

Book Recommendations