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...
You should be able to do this:
Action runMe = () => { Console.WriteLine("Hello World"); };
runMe();
Here's an example of how this might be used. You want to initialize a constructor with the result of a few lines of code that can't be written as a function because that is how the 3rd party API is structured.
It is just glue code to prevent writing a standalone function that is never called anywhere else. I'm using Func
instead of Action
, but the answer is the same as user166390.
// imagine several dozens of lines that look like this
// where the result is the return value of a function call
fields.Add(new ProbeField(){
Command = "A",
Field = "Average",
Value = be.GetAverage()
});
// now you need something that can't be expressed as function call
// so you wrap it in a lambda and immediately call it.
fields.Add(new ProbeField(){
Command = "C",
Field = "Cal Coeff",
Value = ((Func<string>)(() => {
CalCoef coef;
Param param;
be.GetCalibrationCoefficients(out coef, out param);
return coef.lowDet1.ToString();
}))()
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With