To cast an integer to an enum
in C#, you can use direct casting or helper methods like Enum.IsDefined
for validation. Here’s a detailed guide:
1. Direct Casting
Use explicit casting if you’re certain the integer corresponds to a valid enum value:
public enum Status { Pending = 0, Active = 1, Inactive = 2 }
int value = 1;
Status status = (Status)value; // Status.Active
2. Validate the Integer First
Use Enum.IsDefined
to check if the integer maps to a defined enum value:
int value = 3;
if (Enum.IsDefined(typeof(Status), value)) {
Status status = (Status)value;
} else {
// Handle invalid value (e.g., throw an error or assign a default)
throw new ArgumentException($"Invalid value: {value}");
}
3. For Non-int
Underlying Types
If the enum uses a non-int
underlying type (e.g., byte
), use Enum.ToObject
:
public enum Priority : byte { Low = 1, Medium = 2, High = 3 }
int value = 2;
Priority priority = (Priority)Enum.ToObject(typeof(Priority), value); // Priority.Medium
4. Handling Undefined Values
Casting works even for undefined values, but the result won’t match a named enum member:
int value = 99;
Status status = (Status)value; // Valid, but no named enum member corresponds to 99
Console.WriteLine(status); // Output: 99
Key Notes
- Default Underlying Type: Enums default to
int
, but you can specify others (e.g.,byte
,long
). - Validation: Always validate untrusted input (e.g., user input) with
Enum.IsDefined
. - Flags Enums: For
[Flags]
enums, integers can represent bitwise combinations of values.
Example Workflow
using System;
public enum Color { Red = 1, Green = 2, Blue = 3 }
public class Program {
public static void Main() {
int input = 2;
if (Enum.IsDefined(typeof(Color), input)) {
Color color = (Color)input;
Console.WriteLine($"Color: {color}"); // Output: Green
} else {
Console.WriteLine("Invalid color value.");
}
}
}
When to Use Which
Method | Use Case |
---|---|
Direct Cast | Trusted values (e.g., hardcoded integers). |
Enum.IsDefined | Validate untrusted input (e.g., user data). |
Enum.ToObject | Non-int underlying types (e.g., byte ). |
By following these methods, you can safely convert integers to enums in C#!