I have a method
String Foo<T> where T: WebControl
Now I do have a string like “hyperlink”. What is want is to call Foo<Hyperlink> based on a mapping from the string to the generic.
How does the dictionary have to look like?
It ain’t:
private Dictionary<string, Type> _mapping = new Dictionary<string, Type>()
{
{"hyperlink", typeof(HyperLink)}
};
I want to access it like Foo<_mapping[mystring]> is that possible? If yes, how must be dictionary look like?
Edit: Accepted Solution
String _typename = "hyperlink";
MethodInfo _mi = typeof(ParserBase).GetMethod("Foo");
Type _type = _mapping[_typename];
MethodInfo _mig = _mi.MakeGenericMethod(_type);
return (String)_mig.Invoke(this, new object[] { _props }); // where _props is a dictionary defined elsewhere
// note that the first parameter for invoke is "this", due to my method Foo is not static
What you want isn’t possible, as that would be runtime (e.g. the dictionary could contain anything later).
If you want to manually generate it via runtime, you can do so, but you won’t get the compile-time checking C# has on generics. You can to this via MethodInfo.MakeGenericMethod.
Like this: