The context of the this question is an MVC app that takes strings and hopefully converts them to types and hands them off to generic code.
- I have a string representation of a type for input.
- I can’t seem to ever put a
Typevariable inside the<>for a generic method. - Does that mean I have to manually spell out all the possible cases and generic method calls? Is that the right way to do this?
- It would be cool if a
ModelBindercould figure out the type somehow where I could have a generic type parameter for an Action Methodpublic ActionResult Something<T>(). But I don’t know if that is possible.
example
public ActionResult DoSomething(string typeName, int? id)
{
var type = Type.GetType(typeName);
if (type == typeof(Apple)) DoSomethingElse<Apple>(id);
if (type == typeof(Orange)) DoSomethingElse<Orange>(id);
//if etc ... to infinity
}
If you only have the type then you’d have to all it via reflection. Assuming “DoSomethingElse” is a method in the current class:
That SHOULD work for you, although you should note, it’s not going to be pretty! 😉