Logo

How do I cast int to enum in C#?

Casting an int to an enum in C# is a common requirement when you have an integer representation—perhaps from a database or user input—and need to convert it to a strongly typed enum. Below, you’ll learn how to safely cast integers to enums, handle invalid values, and follow best practices.

Using Direct Casting

C# allows you to directly cast an integer to an enum type using a simple cast expression. For example:

public enum OrderStatus { Pending = 0, Processing = 1, Completed = 2, Cancelled = 3 } int statusValue = 2; OrderStatus status = (OrderStatus)statusValue; Console.WriteLine(status); // Outputs "Completed"
  • How It Works: If statusValue matches the underlying integer value of an enum member, the resulting enum variable will be correctly assigned (e.g., 2 maps to OrderStatus.Completed).
  • Implicit Behavior: C# doesn’t automatically check if the integer is a valid enum value. A value of 99, for example, will still cast to the enum type but won’t match any named constant unless you explicitly verify.

Checking for Valid Enum Values

Sometimes, the integer you’re casting might not match a defined enum member. In these cases, you might accidentally end up with an undefined value. Use the Enum.IsDefined method or a validation check to be safe:

int invalidValue = 99; if (Enum.IsDefined(typeof(OrderStatus), invalidValue)) { OrderStatus validStatus = (OrderStatus)invalidValue; Console.WriteLine($"Casted to {validStatus}"); } else { Console.WriteLine("Invalid value for OrderStatus enum."); }
  • When to Use: If your data can come from external sources like user input or a database, always validate the integer before casting.

Handling Unknown Values

If an integer value does not exist in your enum definition and you need to handle it gracefully, consider:

  1. Using a Default Enum Member: Some developers add an Unknown or None member to the enum to handle unmapped integer values.
  2. Throwing an Exception: If the application requires strict enforcement, throw an exception when the cast results in an undefined enum value.

Best Practices

  1. Validate External Inputs: Always check Enum.IsDefined or similar logic before casting integers from external sources.
  2. Use Meaningful Names: Enums should have descriptive names and be self-explanatory, making them easier to read when casting or debugging.
  3. Flag Enums: If you’re dealing with [Flags] enums, casting might result in combined values—ensure your code logic accounts for that.

Expand Your C# and .NET Skills

If you want to broaden your C# knowledge and master coding patterns, consider exploring courses that emphasize hands-on, pattern-based learning. DesignGurus.io offers:

These courses not only refine your coding fundamentals but also highlight best practices for handling common language features like enums. For additional insights and advanced interview tips, check out DesignGurus.io’s YouTube channel.

Casting an integer to an enum ultimately boils down to (EnumType)intValue and verifying that it’s valid. This approach strengthens type safety, readability, and reduces logical errors in your C# applications.

CONTRIBUTOR
TechGrind