object to enum conversion: How generic can it get?

I need to write a dozen of helper functions which will convert an object to enum types. I need to write these seperate functions because the enum types are different. My question is, can I achieve this with just one function

i.e. can I merge the following two functions into one

public enumTypeOne GetOne(object o)
{
enumTypeOne one = (enumTypeOne) Enum.Parse(Type.GetType("enumTypeOne"), o.ToString());

return one;
}

public enumTypeTwo GetOTwo(object o)
{
enumTypeTwo one = (enumTypeTwo) Enum.Parse(Type.GetType("enumTypeTwo"), o.ToString());

return two;
}


Can I have one generic function (which probably will take a reference argument to store the return value) which can achieve the functionality of both the functions


Answer this question

object to enum conversion: How generic can it get?

  • andyedw

    Thanks AndreJ, this is what exactly what I am doing.

    Thanks once again,
    J

  • Daikoku

    Ok, sorry for posting before doing enough research. I got the answer. I will templatize the function and I am done. Wow, I think I like C#.

  • arcLee

    OK, glad you got it going. However, writing an answer, I came up with this so far... hope it helps. You'll have to add some additional type checking to be more bulletproof [see comments]:

    public enum Alpha { One, Two, Three }
    public enum Beta { Four, Five, Six }

    public class GenericEnums
    {
    public T GetOne<T>(object o)
    {
    T one = (T)
    Enum.Parse(typeof(T), o.ToString());
    return one;
    }

    public void Test()
    {
    MessageBox.Show(GetOne<Alpha>(Alpha.One).ToString()); // OK
    MessageBox.Show(GetOne<Beta>(Beta.Six).ToString()); // OK
    MessageBox.Show(GetOne<Alpha>(Beta.Six).ToString()); // Exception
    }
    }

    Andrej



  • object to enum conversion: How generic can it get?