user9969
user9969

Reputation: 16040

Converting enum to enum not working when are not in same order

Working on a project where they have lots of enums and lots of duplicated objects across multiple dlls. A mess but lets move on.

I have this extension method that works when converting an Enum to Enum that have the same position in the enum however it fails if the name is the same but the position of the enum is different

How can Improve my code so that it gets the correct enum based on name match regardless where is located in the enum

Thanks

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void ToEnum_convert_returnsCorrectEnum()
        {
            const CategoryA categoryALawyer = CategoryA.Lawyer;
            var result = categoryALawyer.ToEnum<CategoryB>();

            Assert.AreEqual(CategoryA.Lawyer.ToString(),result.ToString());
        }
    }


    namespace Utilities
    {
        public enum CategoryA
        {
            Lawyer,
            Developer,
            Manager,
            Employee,
            Director,

        }

        public enum CategoryB
        {
            Director,
            Manager,
            Developer,
            Employee,
            Lawyer
        }

        public static class EnumExtensions
        {
            public static T ToEnum<T>(this Enum value)
            {
                return (T)Enum.ToObject(typeof(T), value);
            }               
        }
    }

EDIT

Some dlls I have no control over so I cannot change enum order

Upvotes: 2

Views: 169

Answers (1)

McGarnagle
McGarnagle

Reputation: 102743

T val;
if (Enum.TryParse<T>(value.ToString(), out val))
    return val;
else return default(T);

Edit: changed "Parse" to the correct "TryParse". Also, the TryParse method has an overload to make it case-insensitive if you want:

Enum.TryParse<T>(value.ToString(), true, out val)

Upvotes: 7

Related Questions