How to extract generic method constraints via reflection in C#?
Asked Answered
F

2

5

Given an object of type System.Reflection.MethodInfo how can I extract generic parameter constraints? Somehow I can not find reasonable information about this.

Frazzled answered 18/11, 2015 at 8:57 Comment(1)
This answer may help you: How to determine if ParameterInfo is of generic type?Thorny
D
7

All you need to do is grab the generic method definition, and list the generic arguments on that:

method
.GetGenericMethodDefinition()
.GetGenericArguments()
.Select(i => i.GetGenericParameterConstraints())
.Dump();

However, note that this doesn't 100% correspond to C#'s generic type constrains - there's a bit of wiggle room. Still, if you only care about e.g. a base-type constraint, it will work fine :)

As an example, class isn't actually a type constraint at all, interestingly, while struct is "translated" as System.ValueType (not too surprising). new() isn't a type constraint either, so this method doesn't work to find that.

If you need to take those constraints into account as well, use the GenericParameterAttributes property in the Select. For example, struct constraint will give you NotNullableValueTypeConstraint | DefaultConstructorConstraint.

Definition answered 18/11, 2015 at 9:8 Comment(2)
Thank you for your answer! That's what I was looking for. I did not know that if I have a method type (retrieved from a type representing a class) I still need to get the method definition. I thought a class type would already return method definitions which obviously it does not???Frazzled
@RegisMay Generic is the keyword here - the generic method definition is less specific than the specific (reified) one you have in hand. This applies to both generic types and generic methods. For example, if you list all generic methods of a generic type that isn't reified, you will get the generic method definitions as you'd expect and you can skip the GetGenericMethodDefinition call. If in doubt, ask yourself - can I invoke this method (or instantiate a type)? If the answer is yes, your method (or type) is reified, and you'll need to get the generic-er method (or type).Definition
T
0

You are probably looking for Type.GetGenericParameterConstraints Method ()

Returns an array of Type objects that represent the constraints on the current generic type parameter.

Also Type.GetGenericArguments Method ()

Returns an array of Type objects that represent the type arguments of a closed generic type or the type parameters of a generic type definition

Tortuosity answered 18/11, 2015 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.