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 ints 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:

    public enum Gender
        Male = 1
        Female = 2

Get the int value from an Enum-member

    int female = (int)Gender.Female;

Get the Enum-member from an integer

    Gender gender = (Gender)1;

Convert the name of the Enum-member to a string

    string female = Gender.Female.ToString();

or use the fancier way of C# 6.0:

    string gender = nameof(Gender.Female);

Convert a string into an Enum-member

    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