Search code examples
c#genericsreflectionmethodinfoparameterinfo

How to determine if ParameterInfo is of generic type?


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?


Solution

  • 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.