5

Lets say, If I have a situation like the following.


Type somethingType = b.GetType();
    // b is an instance of Bar();

Foo<somethingType>(); //Compilation error!!
    //I don't know what is the Type of "something" at compile time to call
    //like Foo<Bar>();


//Where:
public void Foo<T>()
{
    //impl
}

How should I call the generic function without knowing the type at compile time?

123Developer
  • 1,463
  • 3
  • 17
  • 24
  • 1
    possible duplicate of [C# specifying generic collection type param at runtime](http://stackoverflow.com/questions/513952/c-specifying-generic-collection-type-param-at-runtime) – Andrey Aug 24 '10 at 09:23
  • 1
    any many other. please use search before asking. – Andrey Aug 24 '10 at 09:23
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 13:34

1 Answers1

12

You'll need to use reflection:

MethodInfo methodDefinition = GetType().GetMethod("Foo", new Type[] { });
MethodInfo method = methodDefinition.MakeGenericMethod(somethingType);
method.Invoke();

When writing a generic method, it's good practice to provide a non-generic overload where possible. For instance, if the author of Foo<T>() had added a Foo(Type type) overload, you wouldn't need to use reflection here.

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138