The complete guide to cast different types to and from enums in .NET Core

Enumerations are a great way to standardize your code and move away from using string literals or integers for if-conditions. For example using this Gender gender = Gender.Female instead of this string gender = "Female" is much cleaner and you get a single point of change in the Enum. However, since you might dealing with legacy code, you will have to cast the strings or integers to your Enumerations when connecting new with old code. Lets see how this is done.

For our examples we will use the Gender Enum, with two members:

1
2
3
4
5
    public enum Gender
    {
        Male = 1
        Female = 2
    }

Get the int value from an Enum-member

1
    int female = (int)Gender.Female;

Get the Enum-member from an integer

1
    Gender gender = (Gender)1;

Convert the name of the Enum-member to a string

1
    string female = Gender.Female.ToString();

or use the fancier way of C# 6.0:

1
    string gender = nameof(Gender.Female);

Convert a string into an Enum-member

1
    Enum.TryParse("Female", out Gender gender);

This example also use the C# 7.0 feature of inline out variable, so the variable gender will take the Gender.Female value.

Hints and tips about Enums

comments powered by Disqus