I like to send a generic type converter function to a method but I can\'t figure out how to do it.
Here\'s invalid syntax that explains what I like to achieve, the p
You cannot have instances of generic functions or actions - all type parameters are defined upfront and cannot be redefined by the caller.
An easy way would be to avoid polymorphism altogether by relying on down-casting:
public void SomeUtility(Func converter)
{
var myType = (MyType)converter(typeof(MyType), "foo");
}
If you want type safety, you need to defer the definition of the type parameters to the caller. You can do this by composing a generic method within an interface:
public void SomeUtility(IConverter converter)
{
var myType = converter.Convert("foo");
}
interface IConverter
{
T Convert(object obj);
}
Edit:
If the 'converter type' is known at the call-site, and only this type will be used inside the utility method, then you can define a generic type on the method and use that, just like other posters have suggested.