I've got this generic method, and I want to make sure that the types specified are enums.
Now I understand I can't do something like where T:enum
. But I want to make sure in runtime.
I know I could do it like typeof(T).IsENum
. But I want to use reflection like so
public static List<Tuple<T, Y>> Produce<T, Y>()
where T: struct, IConvertible
where Y: struct, IConvertible
{
var methodInfo = System.Reflection.MethodBase.GetCurrentMethod();
foreach(var typeInMethod in methodInfo.GetGenericArguments())
CheckTypeIsEnum(typeInMethod);
The problem is that the types returned by methodInfo.GetGenericArguments() aren't of the enum types I specified. But instead they are of type T
and Y
and BaseType: {Name = "ValueType" FullName = "System.ValueType"}
.
Summarized: How do I get an array of all generic types used in the method?
P.S. .Net 4.5
You should just use typeof(T)
and typeof(Y)
- those will give you the actual generic type arguments. There's no benefit to using reflection here: it's slow and gives you the wrong answers! As far as I'm aware, the generic type arguments simply aren't available with reflection at execution time. In particular, the method you're currently calling (MethodBase.GetCurrentMethod
) explicitly documents that your approach will not work:
If the currently executing method is a generic method,
GetCurrentMethod
returns the generic method definition.
(In other words, the version which doesn't have the type arguments specified - it only knows that you've got T
and Y
, but not what they are.)
So just get rid of your loop, and use:
CheckTypeIsEnum(typeof(T));
CheckTypeIsEnum(typeof(Y));
Also note that with a bit of IL hackery, you can have a constraint of where T : enum
. It's not valid C#, but it's valid IL and the C# compiler obeys the constraint in IL it's looking at :) See my Unconstrained Melody project for an example.
See more on this question at Stackoverflow