Reputation: 117
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.
Upvotes: 1
Views: 464
Reputation: 5213
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:
Upvotes: 1