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:
Get the int value from an Enum-member
Get the Enum-member from an integer
Convert the name of the Enum-member to a string
or use the fancier way of C# 6.0:
Convert a string into an Enum-member
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.