I would like to write an extension method for a generic type with additional parameters of a generic type. I already have working code, but I donโt like the result, because the user must re-enter the type parameters of the existing type.
I have a specific example, but keep in mind that this is a common problem. I appreciate feedback on a specific problem, but I am looking for common solutions.
For a class like Action<T> add an extension method with a signature like this:
Func<T, TResult> ToFunc<TResult>();
Here is my working code:
public static class DelegateExtensions { public static Func<T, TResult> ToFunc<T, TResult>(this Action<T> action) { return arg => { action(arg); return default(TResult); }; } }
But use stinks:
public void TakesAFunc(Func<int, float> someFunc) { }
In this example, the generic int parameter is the only valid value, so it causes unnecessary code duplication.
Type inference doesn't work here. I think this is because you cannot infer a generic parameter through the return type.
This code will solve the problem, but unfortunately does not work:
public static class DelegateExtensions<T> { public static Func<T, TResult> ToFunc<TResult>(this Action<T> action) { return arg => { action(arg); return default(TResult); }; } }
Usage will be as you expected:
public void TakesAFunc(Func<int, float> someFunc) { }
I noticed that System.Linq.Queryable works like my first piece of code, although usually it doesn't need additional type parameters, so type inference works.
Is there any known trick requiring these repeating typical type parameters? One thought that comes to mind will be code generators or macros, but I can't figure out how I would do it cleanly.