How to determine if ParameterInfo is of generic type?
Asked Answered
M

4

7

I have a MethodInfo of a GenericMethodDefinition. Such as: CallMethod<T>(T arg, string arg2). The GetParameters() method will give me two ParameterInfo objects, the first of which is generic, the second of which is not. How can I get ParameterInfo to tell me it is generic? What about if it has constraints?

Mika answered 19/1, 2011 at 17:56 Comment(1)
thanks to the mods for creating the parameterinfo tagMika
P
7

Check ParameterType.IsGenericParameter.
You may also want to check ContainsGenericParameters, which will be true for something like MyMethod<T>(List<T> param). (Even though List<> isn't a generic parameter)

If IsGenericParameter is true, you can also call GetGenericParameterConstraints() to get interface or base type constraints, and you can check GenericParameterAttributes (a [Flags] enum) for new(), struct, or class constraints.

Pahari answered 19/1, 2011 at 17:59 Comment(2)
what about generic parameter constraints?Mika
In case args is an array of T[] one may use ParameterType.IsArray and ParameterType.ContainsGenericParameter.Coruscation
D
3

I think you are looking for these:

parameterInfo.ParameterType.ContainsGenericParameters
parameterInfo.ParameterType.GetGenericParameterConstraints()
Downhaul answered 19/1, 2011 at 18:0 Comment(0)
H
2

In additional to others' answer to the second question: Yes we can get the constraints from ParameterInfo using GetGenericParameterConstraints(), but it doesn't work for all circumstances. Consider some generic method like this:

public static void MyMethod<T,V>() where T : Dictionary<int, int>
{
}

There is a constraint for this method, but the method doesn't have parameters(think about Enumerable.Cast). What I'm going to say is the constraint is not part of the parameters, but the method itself. We can get the constraints by:

method.GetGenericArguments()[0].BaseType  //the constraint of T
method.GetGenericArguments()[1].BaseType  //that of V: Object
Huneycutt answered 19/1, 2011 at 18:21 Comment(0)
M
1

Maybe here you will find information about reflecting generic parameters ...

Medusa answered 19/1, 2011 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.