Black Light
Black Light

Reputation: 2404

How to convert between Enums where values share the same names?

If I want to convert between two Enum types, the values of which, I hope, have the same names, is there a neat way, or do I have to do it like this:

enum colours_a { red, blue, green }
enum colours_b { yellow, red, blue, green }

static void Main(string[] args)
{
    colours_a a = colours_a.red;
    colours_b b;

    //b = a;
    b = (colours_b)Enum.Parse(typeof(colours_b), a.ToString());
}

?

Upvotes: 16

Views: 12510

Answers (4)

you can use Extensions:

public static class EnumExtensions
{
    public static TTarget ConvertTo<TTarget>(this Enum sourceEnum) where TTarget : struct, Enum
    {
        if (!typeof(TTarget).IsEnum)
            throw new ArgumentException("TTarget must be an enum type.");

        if (!Enum.IsDefined(typeof(TTarget), sourceEnum.ToString()))
            throw new ArgumentException($"Invalid mapping from {sourceEnum.GetType()} to {typeof(TTarget)}.");

        string sourceName = sourceEnum.ToString();
        string targetName = Enum.GetName(typeof(TTarget), sourceEnum);

        return (TTarget)Enum.Parse(typeof(TTarget), targetName);
    }
}

Upvotes: 0

Michael Buen
Michael Buen

Reputation: 39453

Use this (encapsulate variables to new class as needed):

class Program
{

    enum colours_a { red, green, blue, brown, pink }
    enum colours_b { yellow, red, blue, green }

    static int?[] map_a_to_b = null;

    static void Main(string[] args)
    {
        map_a_to_b = new int?[ Enum.GetValues(typeof(colours_a)).Length ];

        foreach (string eachA in Enum.GetNames(typeof(colours_a)))
        {

            bool existInB = Enum.GetNames(typeof(colours_b))
                            .Any(eachB => eachB == eachA);

            if (existInB)
            {
                map_a_to_b
                    [
                    (int)(colours_a)
                    Enum.Parse(typeof(colours_a), eachA.ToString())
                    ]

                    =

                    (int)(colours_b)
                    Enum.Parse(typeof(colours_b), eachA.ToString());
            }                                   
        }

        colours_a a = colours_a.red;
        colours_b b = (colours_b) map_a_to_b[(int)a];
        Console.WriteLine("Color B: {0}", b); // output red

        colours_a c = colours_a.green;
        colours_b d = (colours_b)map_a_to_b[(int)c];
        Console.WriteLine("Color D: {0}", d); // output green
        Console.ReadLine();

        colours_a e = colours_a.pink;
    // fail fast if e's color don't exist in b, cannot cast null to value type
        colours_b f = (colours_b)map_a_to_b[(int)e]; 
        Console.WriteLine("Color F: {0}", f);
        Console.ReadLine();

    }// Main
}//Program

Upvotes: 2

Jo&#227;o Angelo
Jo&#227;o Angelo

Reputation: 57718

You can also do this, don't know if it's neat enough:

enum A { One, Two }

enum B { Two, One }

static void Main(string[] args)
{
    B b = A.One.ToB();
}

This of course requires an extension method:

static B ToB(this A a)
{
    switch (a)
    {
        case A.One:
            return B.One;
        case A.Two:
            return B.Two;
        default:
            throw new NotSupportedException();
    }
}

Upvotes: 6

Richard Szalay
Richard Szalay

Reputation: 84804

If you have strict control over the two enum's, then your solution (or Randolpho's) is fine.

If you don't, then I'd skip trying to be tricky and create a static mapping class that converts between them. In fact, I'd probably recommend that anyway (even if you map by name there for now), from an ease-of-maintenance perspective.

Upvotes: 7

Related Questions