C# - How to convert an int to an enum or an enum to an int.

This post shows how to convert an int to an enum or an enum to an int. You do not use a convert method, but rather cast it. For this post we will use the following example of an enum:

enum options
    first = 1,
    second = 2

Note: you do not have to define the value (1 and 2) behind each item in the enum. You can leave some or all without declaring their value explicitly. We will start by going from int to enum.

Casting an int to an enum

Using the above we can cast an int (1) to our options enum:

var k = 1;
var asEnum = (options)k;

This will give us an enum type of "first". You might wonder what happens if you try to cast the number 3 instead:

var k = 3;
var asEnum = (options)k;

You coould assume that the above ends up with an exception but it does not. This is because enums are not checked, they can have any value of the underlying type, So the above can have any value that an int can have. You can check if the value is defined in the enum by using the IsDefined method:

var k = 3;
var asEnum = (options)k;

var isDefined = Enum.IsDefined<options>(asEnum);
//isDefined is false

Getting the underlying int from an enum

We can get the underlying value of the enum by casting it to an int:

var k = options.first;
var asInt = (int)k;

Yes, enums can contain other underlying types than integers. This post uses integers as I believe it is the most common.

That is all

I hope you found the above helpful, please leave a comment down below with your thoughts!