C# - Cast int to enum

C# - Cast int to enum

c#, c# enum to int, c# int to enum, 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. Check out our examples below on how to convert int to enum using C#.

What is an enum?

An enumeration or "enum" is a value type data type which consists of a list of named integer constants. As illustrated in the examples below, an enumeration can be defined by using the enum keyword. Using the enum data type we are able to assign each integer constant to a name. Also note that each name must be unique within the scope of that particular enum, remember these are named integer constants

Casting to and from a Color enum

We hope the brief enum explanation was helpful. Check out our examples below which show how to cast an enum to an int or check if enums exist by integer or name.

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

Looking for more progamming tutorials?

Check out C# iterate dictionary to learn more about looping and manipulating dictionaries.

Back to The Programmer Blog