1

I have a series of generic methods that accept a type to run. For instance:

db.CreateTable<MyClassName>();

I want to be able to create a list of classes and then iterate over the list like:

foreach(var class in classList)
{
    db.CreateTable<class>();
    db.CheckStatus<class>();

    // ... etc
}

VS says the parameter is a method group. I googled this and docs say this is a delegate. How do i create a list of delegates pointing to my classes that I can then iterate over and use as reference in call to generic method?

Guerrilla
  • 13,375
  • 31
  • 109
  • 210
  • you cannot (simply) vary the type bound to a generic at run time, its a compile time thing. Does this need to be a generic, why not a method that simply accepts a Type as an arg. – pm100 Oct 26 '18 at 20:19

1 Answers1

3

My answer makes an assumption I just realized might not be valid: I am assuming that classList is a IEnumerable<Type>. If that is incorrect, my answer will need to be revised.

It needs to be something like this.

var fn = db.GetType().GetMethod("CheckStatus");

foreach (var cls in classList)
{
    var fn2 = fn.MakeGenericMethod(cls);
    fn2.Invoke(db, null);
}

Okay, what's going on here. We get a reference to the method on the db object called "CheckStatus". If there are overloads of that method, you'll need to use one of the overloads of GetMethod to get it.

Then, we make it a closed generic method. So in the first part, we get a method CheckStatus<T>, where T is not specified. This is an open generic. You need to fill in the generic with your type information. That is what MakeGenericMethod does. In effect, it gives you CheckStatus<cls>. You can then invoke this method on db.

For more information on open/closed generics, see: What exactly is an “open generic type” in .NET?