It's hot, cool down with FREE SHIPPING! Use code SUMMER17

C# - Cast int to enum

C# - Cast int to enum

c#, cast, enum, int, string

Casting enums can get tricky in C# so we wanted to provide a few examples to help clarify the situation. Below we are using a simple enum to demonstrate how to cast an int to a enum, enum to an int. We will also go over how to check if an enum exists given an integer or string and how to iterate enums. 

Casting to and from a Color enum

Given the enum

public enum Color {
    Red = 1,
    Green = 2,
    Blue = 3

Casting to enum from an int

Color c = (Color)3; 
//Result: c = Blue

Color c = (Color)4;
//Result: c = 4

Casting to int from an enum

int i = (int)Color.Blue;
//Result: i = 3

Check if the enum value exists given an integer

bool enum3IsDefined = Enum.IsDefined(typeof(Color), 3);
bool enum4IsDefined = Enum.IsDefined(typeof(Color), 4);
// enum3IsDefined = true
// enum4IsDefined = false

Check if the enum value exists given a string

Color blue;
Color black;
bool blueParseResult = Enum.TryParse("Blue", out blue);
bool blackParseResult = Enum.TryParse("Black", out black);
// blueParseResult = true
// blackParseResult = false
// blue = 3
// black = 0

Enumerate a list of enums

foreach (Color color in Enum.GetValues(typeof(Color)))
    //Do something with color