tags:

views:

73

answers:

2

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?

+5  A: 

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
SWEET!!! got my upvote!
Nissim
Just one correction: MethodInfo method = methodDefinition.MakeGenericMethod(somethingType);
Nissim
Thanks, corrected. This one must have slipped past my Stack Overflow Unit Test Suite.
Tim Robinson
@Tim?What if the function "Foo<T>()" is an extension method to the type. Would it be listed in MethodInfo[]? or GetMethod(..)?
123Developer
No, it'll be a static method on whichever class defines the extension method
Tim Robinson
A: 

You can use the reflection method already stated, but that defeats the purpose of generics.

Jamiec