convert an enum to another type of enum

Given Enum1 value = ..., then if you mean by name:

Enum2 value2 = (Enum2) Enum.Parse(typeof(Enum2), value.ToString());

If you mean by numeric value, you can usually just cast:

Enum2 value2 = (Enum2)value;

(with the cast, you might want to use Enum.IsDefined to check for valid values, though)


Just cast one to int and then cast it to the other enum (considering that you want the mapping done based on value):

Gender2 gender2 = (Gender2)((int)gender1);

Using an extension method works quite neatly, when using the two conversion methods suggested by Nate:

public static class TheirGenderExtensions
{
    public static MyGender ToMyGender(this TheirGender value)
    {
        // insert switch statement here
    }
}

public static class MyGenderExtensions
{
    public static TheirGender ToTheirGender(this MyGender value)
    {
        // insert switch statement here
    }
}

Obviously there's no need to use separate classes if you don't want to. My preference is to keep extension methods grouped by the classes/structures/enumerations they apply to.


If we have:

enum Gender
{
    M = 0,
    F = 1,
    U = 2
}

and

enum Gender2
{
    Male = 0,
    Female = 1,
    Unknown = 2
}

We can safely do

var gender = Gender.M;
var gender2   = (Gender2)(int)gender;

Or even

var enumOfGender2Type = (Gender2)0;

If you want to cover the case where an enum on the right side of the '=' sign has more values than the enum on the left side - you will have to write your own method/dictionary to cover that as others suggested.

Tags:

C#

Enums