Assuming I have this function:
Func<string> fs = () => "test";
var st = fs();
I want to simplify this to:
var st = (()=> "test")();
It seems however that I can’t define the function and then instantly invoke it. Is this possible in another way?
This is possible:
var st = (new Func<string>(() => "test"))();
But very messy.
To clarify is it possible to define an anonymous function without have to specify the delegate type being used, i.e. is there a way to get the compiler to infer the types directly from the function?
You need to specify the type somehow. Others have shown how to do this inline.
There is another possibility: Create a helper method. Because the parameter of the method is defined, you don’t have to define the type yourself when calling the method.
Usage: