tags:

views:

101

answers:

3

Hi,

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());
}

Thanks,

Ross

+1  A: 

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.

Richard Szalay
I would have to agree — whilst it's possible to cast from one t'other a mapping function would be more transparent and less prone to error.
Paul Ruane
A: 

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();
    }
}
João Angelo
A: 

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
Michael Buen