ssb.serman
ssb.serman

Reputation: 155

Call generic method by type

I have these classes:

public static class A{
    ...
   public C Run<T>(string something)
   {
       ...
   }
}

public static class B{
    ...
    public void Exec<T>(Type type)
    {
        MethodInfo method = typeof(A).GetMethod("Run");
        MethodInfo generic = method.MakeGenericMethod(type);
        var result = generic.Invoke(null, new object[] { "just a string" });
        // bad call in next line
        result.DoSomething();
    }
}


public class C{
    ...
    public void DoSomething(){}
}

How to convert result to type for call DoSomething method? And how simpler to call generic method using type variable?

Upvotes: 1

Views: 942

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

How to convert result to type for call DoSomething method?

You cannot do that statically, because your code does not know the type at compile time, and the object is already of the correct type. One way to do it in .NET 4.0 and later is to use dynamic instead of object for the result, like this:

dynamic result = generic.Invoke(null, new object[] { "just a string" });
result.DoSomething(); // This will compile

You can do it like this only if you are 100% certain that the DoSomething() method is going to be there at runtime. Otherwise, there is going to be an exception at runtime, which you would need to catch and process.

Upvotes: 1

Related Questions