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-comparisons in your code. For example using this Gender gender = Gender.Female instead of this string gender = Female is much cleaner and one change in the Enum affects the whole application. However, since you might dealing with legacy code, you will have to cast the strings or ints to your Enumerations when connecting new with old code. Lets see how this is done.

In the following examples we are going to 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

  • Keep the Enums of your application in a central cross-cutting component, so that you reuse them and do not redefine them in different places inside the application. Doing this way you are avoiding unneeded castings from one type to another.

  • If you are using Swagger client for your WebAPIs, configure the namespaces of the Enumerations, so that the client does not generate a new type for each Enum.

comments powered by Disqus