1

How can I cast my own enum type to generic enum type ?

public enum MyEnum
    {
        First,
        Second
    }

    public class MyEnumParser<TEnum>
        where TEnum : struct, Enum
    {
        public static TEnum Parse(string value)
        {
            switch (default(TEnum))
            {
                case MyEnum _: return MyEnum.First;  // Error in this line of code
                default: throw new ArgumentOutOfRangeException($"Type {nameof(TEnum)} not supported.");
            }
        }
    }

The compiler won't let me convert the type, even though I'm explicitly checking the type in the switch:

Cannot implicitly convert type 'ConsoleApp1.MyEnum' to 'TEnum'

If I try to explicitly cast the type, I get another error:

case MyEnum _: return (TEnum)MyEnum.First;

Cannot convert type 'ConsoleApp1.MyEnum' to 'TEnum'

Upd. I am currently working on System.Text.JSON serializer. This is simplified example.The method must be generic. Gradually, I will add all my other enumerations to the serializer. I started with one.

Michael Zagorski
  • 107
  • 1
  • 10
  • What is the end goal? If you know which values to check before hand, thus know the type of enum, you wouldn't need it to be generic? (As for parsing, there are several Enum.Parse methods available. Would they do what you need?) – Me.Name May 19 '20 at 11:29
  • It seems that the TEnum is not needed here if you are going to return known types. – Ross Bush May 19 '20 at 11:32
  • You may alread know this but you can assign a enum member to 0 and it will be default(TEnum). – Ross Bush May 19 '20 at 11:33
  • I am currently working on System.Text.JSON serializer. This is simplified example.The method must be generic. – Michael Zagorski May 19 '20 at 11:34
  • 1
    You can use the next approach: `case MyEnum _: return (TEnum) (object) MyEnum.First;`. But is it acceptable for you? Are you fine with additional cast to `object`? – Iliar Turdushev May 19 '20 at 12:02
  • @Iliar Turdushev Yes, casting to object works. Can you write this as an answer ? I'll take it, because it seems to work, but I'm not sure it's the right way. – Michael Zagorski May 19 '20 at 12:21

1 Answers1

1

The simplest way to cast your custom enum type MyEnum to generic enum type TEnum is to use the next approach:

case MyEnum _: return (TEnum) (object) MyEnum.First;

Here are links to similar problems:

Iliar Turdushev
  • 4,935
  • 1
  • 10
  • 23