Basically, Vladโs answer is correct, and you donโt need to declare the lambda function in advance as a delegate.
Also, in C #, the situation is not so simple, because the compiler cannot decide whether the syntax lambda expression should be compiled as a delegate (e.g. Func<int> ) or an expression tree (e.g. Expression<Func<int>> ), and It can also be any other compatible type of delegation. So you need to create a delegate:
int foo = new Func<int>(() => { Console.WriteLine("bar"); return 1; })();
You can simplify the code a bit by specifying a method that just returns a delegate and then calling a method - the C # compiler automatically infers the delegate type:
static Func<R> Scope<R>(Func<R> f) { return f; } // Compiler automatically compiles lambda function // as delegate and infers the type arguments of 'Scope' int foo = Scope(() => { Console.WriteLine("bar"); return 1; })();
I agree that this is an ugly trick that cannot be used :-), but it is an interesting fact that it can be done!
Tomas petricek
source share