Execute lambda expression immediately after its definition?
You should be able to do this:
Action runMe = () => { Console.WriteLine("Hello World"); };
runMe();
Sure.
new Action(() => { Console.WriteLine("Hello World"); })();
That should do the trick.
Another "option", which is just the other two answers in a slightly different guise:
((Action)(() => { Console.WriteLine("Hello World"); }))();
The reason, as directly taken from phoog's comment:
...you haven't told the compiler whether you want an
Action
or anExpression<Action>
. If you cast that lambda expression toAction
, you'll be able to call Invoke on it or use the method-call syntax () to invoke it.
It sure gets ugly though, and I do not know of a place where this form is ever useful, as it cannot be used for recursion without a name...