Check if method return type is based on generic parameter

695 views Asked by At

When I have a MethodInfo how can I check if the return type is based on a generic parameter?

public class GenericClass<T>
{
  public class InnerClass 
  {
    public static T A()
    {
      return default(T);
    }
  }       
}

When I check

typeof(GenericClass<>.InnerClass).GetMethod("A").ReturnType.IsGenericParameter

I get true but what if I only have a (closed) MethodInfo of a GenericClass<int> for example? Do I have to walk up the path of nested types and check if one has IsGeneric == true then get the GenericTypeDefinition of this type then walk the path down by instantiating open Types until I can create an open version of the MethodInfo or is there an easier (and faster) way?

1

There are 1 answers

1
xanatos On BEST ANSWER

I stand corrected...

Given:

public class GenericClass<T1>
{
    public class InnerClass<T2>
    {
        public static Tuple<T1, T2, T3> A<T3>()
        {
            return null;
        }
    }
}

Type type = typeof(GenericClass<int>.InnerClass<long>);
var methodInfo = type.GetMethod("A");

MethodInfo method = (MethodInfo)type.Module.ResolveMethod(methodInfo.MetadataToken);

Here it was considered a problem... I use it as a feature :-)