Suppose I want to implement a functional composition, like this:
public Func Compose(Func f, Func g)
{
Adding to lasseespeholt's answer, if you define Compose as an extension method (renamed "Then" so that the result makes more sense):
public static Func<T, T> Then<T>(this Func<T, T> f, Func<T, T> g)
{
return x => g(f(x));
}
you can make this fluent:
var h = toUpper.Then(replicate); // .Then(trim) etc...
The following code would work:
Func<string, string> toUpper = ToUpper;
Func<string, string> replicate = Replicate;
// now the compiler knows that the parameters are Func<string, string>
var h = Compose(toUpper, replicate);
So maybe you can still get the readability improvement you are seeking by defining those variables only once and them reusing them throughout your tests (I'm assuming this is a test utility...)
You could pass Compose
the parameter too, and have it actually evaluate the function; it should be able to infer the parameter type in that case. (You might need to still specify the return type, though.)
Other than that, no, there's no way to infer things like this in C#.
I like Ran´s answer (+1), but I think this make it a little more concise and nice. (Works under the assumption that you have the possibility to redefine the functions as follows.)
Func<string, string> toUpper = s => s.ToUpper();
Func<string, string> replicate = s => s + s;
var h = Compose(toUpper, replicate);