Converting one enum type to another by name

Viewed 407

I have a data entity with the property 'UserType' returned as an Enum and need to convert it to another.

The first enum is (with numbers based on values from the database):

  public enum UserType
    {
        Primary = 100001,
        Secondary = 100002,
        Other = 100003
    }

And this is what I want to convert it to:

    public enum UserType
    {
        Primary,
        Secondary,
        Other
    }

This is in order to set the UserType on this class:

public class UserData
    {
        public UserType UserType{ get; set; }
    }

Something like the following maybe?

 MemberType = MemberType(entity.MemberType.ReadValue())

Does anyone know the best way to do this please?

2 Answers

You can use Enum.Parse/Enum.TryParse:

A.UserType ut1 = A.UserType.Primary;
B.UserData data = new B.UserData();
data.UserType = Enum.TryParse(typeof(B.UserType), ut1.ToString(), true, out object ut2) ? (B.UserType)ut2 : B.UserType.Other;

A and B are just the namespace i have used to differentiate both enums. To simluate it i have used classes:

public class A
{
    public enum UserType
    {
        Primary = 100001,
        Secondary = 100002,
        Other = 100003
    }
}

public class B
{
    public enum UserType
    {
        Primary,
        Secondary,
        Other
    }

    public class UserData
    {
        public UserType UserType { get; set; }
    }
}

If you only need it once or twice, honestly: I'd write it manually:

return value switch {
    Foo.A => Bar.A,
    Foo.B => Bar.B,
    Foo.C => Bar.C,
    _ => throw new ArgumentOutOfRangeException(nameof(value)),
};

In the more general case: something involving ToString() and Enum.Parse, for example:

static TTo ConvertEnumByName<TFrom, TTo>(TFrom value, bool ignoreCase = false)
        where TFrom : struct
        where TTo : struct
        => Enum.Parse<TTo>(value.ToString(), ignoreCase);
Related