Converting one enumeration to another

Despite the article about the evilness of enumerations from my fellow blog writer I want to quickly show you a trick how one enumeration can be converted into another by using an extension method.

Normally if you have two enumerations like:

    public enum EnumerationA
    {
        Planetgeek,
        Rocks,
        TheInternet,
    }

and

    public enum EnumerationB
    {
        TheWebsite,
        Planetgeek,
        Rocks,
        TheInternet,
    }

those two enumerations cannot be easily converted from one to another. With the provided extension method below it is although possible to write the following code:

EnumerationA enumeration = EnumerationA.TheInternet;
EnumerationB convertedEnum = enumeration .Convert<EnumerationB>();

// Would throw an exception!
EnumerationB enumeration = EnumerationB.TheWebsite;
EnumerationA convertedEnum = enumeration .Convert<EnumerationA>();

The cool thing with this extension is, that the generic type TDest has been restricted to be an enumeration by constraining TDest to struct, IComparable, IConvertible, IFormattable. Another cool thing is that this code is fully compatible to .NET Compact Framework 3.5 and can therefore be used on this platform!

    public static class EnumExtensions
    {
        public static TDest Convert<TDest>(this Enum value) where TDest : struct, IComparable, IConvertible, IFormattable
        {
            if (!typeof(TDest).IsEnum)
            {
                throw new Exception("This method can only convert to an enumerations.");
            }

            try
            {
                return (TDest) Enum.Parse(typeof(TDest), value.ToString(), true);
            }
            catch
            {
                throw new Exception(string.Format("Error converting enumeration {0} to enumeration {1} ", value, typeof(TDest)));
            }
        }
    }

Have fun converting enumerations!

About the author

Daniel Marbach

1 comment

  • Maybe it would be better to base convertion on values rather than on string representation:

    enum A
    {
    PlanetGeek,
    Rocks,
    TheInternet
    }

    enum B
    {
    TheWebSite = -1,
    PlanetGeek = A.PlanetGeek,
    Rocks = A.Rocks,
    TheInternet = A.TheInternet
    }

    However I would add this to Thomas’s list of evilness 😉
    and use reference keys instead.

Recent Posts