Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute lambda expression immediately after its definition?

Tags:

c#

lambda

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 an Expression<Action>. If you cast that lambda expression to Action, 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();
            }))()
        });