Reputation: 469
I have a generic function that receives a parameter type T which is forced to be an struct . I would like to know how do I check if that type of of certain Enum type declared, I'm doing something like this:
public static string GetSomething<T>() where T : struct
{
switch (typeof(T))
{
case Type EnumTypeA when EnumTypeA == typeof(T):
Console.WriteLine("is EnumTypeA");
break;
case Type EnumTypeB when EnumTypeB == typeof(T):
Console.WriteLine("is EnumTypeB");
break;
default:
Type type = typeof(T);
return new Exception($"Unsupported type {Type.GetTypeCode(type)}");
}
}
But i'm getting always EnumTypeA even when I send EnumTypeB
This is ideally what I would like to do:
switch (typeof(T))
{
case is EnumTypeA
Console.WriteLine("is EnumTypeA");
break;
case is EnumTypeB
Console.WriteLine("is EnumTypeB");
break;
default:
Type type = typeof(T);
return new Exception($"Unsupported type {Type.GetTypeCode(type)}");
}
Upvotes: 1
Views: 685
Reputation: 1499810
Look at this case:
case Type EnumTypeA when EnumTypeA == typeof(T):
That will always be true (because you're switching on typeof(T)
), and it's unrelated to the type called EnumTypeA
at all. It's equivalent to:
case Type t when t == typeof(T):
What you actually want is:
case Type t when t == typeof(EnumTypeA):
So something like this:
switch (typeof(T))
{
case Type t when t == typeof(EnumTypeA):
Console.WriteLine("is EnumTypeA");
break;
case Type t when t == typeof(EnumTypeB):
Console.WriteLine("is EnumTypeB");
break;
default:
Type type = typeof(T);
return new Exception($"Unsupported type {Type.GetTypeCode(type)}");
}
Personally I'd probably prefer to use if/else for this situation, or possibly a static Dictionary<Type, Action>
, but it's hard to say without knowing more about the real scenario.
Upvotes: 6