How can I name a generic function without knowing the type at compile time?

Let's 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 do I call a generic function without knowing the type at compile time?

+3
source share
1 answer

You will need to use reflection:

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

When writing a universal method, it is recommended to use, if possible, universal overload. For example, if the author has Foo<T>()added overloading Foo(Type type), here you will not need to use reflection.

+11
source

Source: https://habr.com/ru/post/1761277/


All Articles