Annie
Annie

Reputation: 11

C# Break down type parameter in generic method if its a nested class

I am trying to pass a nested class into a generic method to evaluate all of its classes, for example

SharedClass.FindParentClass<GrandParent.Parent.Child>();

Generic Method:

public void FindParentClass<T>() where T: ISomeInterface, new()
{
  //Break down T to all of its classes
}

I want to avoid doing this:

SharedClass.FindParentClass<GrandParent,GrandParent.Parent,GrandParent.Parent.Child>();

Generic method that works for above code:

public void FindParent<TGrandParent, TParent, TChild>() where TGrandParent : IGrandParent, new()
                                                         where TParent : IParent, new()
                                                          where TChild : IChild, new()
{
 //all I have to do now is place the type parameters there where I want them    
}

I am not allowed to change the classes that have been used as type parameters, so every class inherits a different interface and has a public parameter-less constructor.

Upvotes: 1

Views: 485

Answers (1)

Annie
Annie

Reputation: 11

In order to work the way I intended it to, I had to write another (private) generic method that accepts all three type parameters:

private void PerformWith<GrandParent, Grandparent.Parent, GrandParent.Parent.Child>()
{
         //Perform something
}

So in my first generic method, I will use reflection to:

  1. Determine all the parent types - with GetTypeInfo().ReflectedType
  2. To get the new method, make it generic and invoke it.

It looks like this:

public void FindParentClass<T> where T: ISomeInterface, new()
{
   var parentClass = typeof(T).GetTypeInfo().ReflectedType;
   var grandparentClass = parentClass.GetTypeInfo().ReflectedType;

   var method = MethodBase.GetCurrentMethod().DeclaringType.GetMethod("PerformWith", BindingFlags.NonPublic());
   var genericMethod = method.MakeGenericMethod(new Type[] { grandparentClass, parentClass, typeof(T) });
   genericMethod.Invoke(null, null);
}

Upvotes: 0

Related Questions