2

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?

Jordan1993
  • 864
  • 1
  • 10
  • 28
  • Preference: make a mapping that accepts an `OldUserType` and returns a `NewUserType`. Failing that, perhaps `Enum.Parse(OldUserType.Primary.ToString());`? – ProgrammingLlama Apr 09 '21 at 07:40
  • Does this answer your question? [convert an enum to another type of enum](https://stackoverflow.com/questions/1818131/convert-an-enum-to-another-type-of-enum) – Sinatr Apr 09 '21 at 07:45

2 Answers2

2

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; }
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900