Is there a way to invoke a generic function with a type known only at run time?
I’m trying to do something like:
static void bar()
{
object b = 6;
string c = foo<typeof(b)>();
}
static string foo<T>()
{
return typeof (T).Name;
}
Basically I want to decide on the type parameter only at run time, but the function I’m calling depends on the type parameter.
Also I know this can be done with reflections… but it’s not the nicest solution to the problem…
I’m sort of looking for dynamic features in C#…
I’m writhing a bridge between two classes the first one is basically a big tree with different types of of objects (composite by interface) the other is a sort of a “super visitor”.
the supper visitor accepts key-value dictioneries that map types to object it looks like:
dic.Add(object value)
and T is not necessarily the type of the value… a lot of times it isn’t…
I know it’s written poorly, but i can’t fix it…
I can work around it, but only at runtime…
I already did it with reflections, but if there’s a better way to do it without them i would be happy to learn…
Thank you
This is a bit of a hack but you can get
dynamicto do the reflection work for you by something like,Here the dynamic call will extract the type of
band use it as a type parameter forFoo().