Use statement lambdas in C#

[statement lambdas]

The example Use lambda expressions in C# showed how to use lambda expressions to concisely create an anonymous method that takes parameters and returns a value. The following code shows one of the lambda expressions that example used.

private void radF3_CheckedChanged(object sender, EventArgs e)
{
    DrawGraph((float x, float y) => (float)(x * x +
        (y - Math.Pow(x * x, 1.0 / 3.0)) *
        (y - Math.Pow(x * x, 1.0 / 3.0)) - 1)
    );
}

This expression works, but it’s all one statement so it’s length makes it fairly confusing.

Technically, this is called an “expression lambda” because the part of it on the right is an expression that returns some value. Instead of using expression lambdas, the code could use statement lambdas. Statement lambdas contain any number of statements inside braces.

Statement lambdas that return a value must use a return statement just as a method would. Like expression lambdas, statement lambdas can let Visual Studio use inference to figure out the lambda’s parameter types, or you can include the parameter types explicitly.

The following code shows the previous event handler rewritten with a statement lambda.

private void radF3_CheckedChanged(object sender, EventArgs e)
{
    DrawGraph((float x, float y) => 
        {
            float temp = (float)(y - Math.Pow(x * x, 1.0 / 3.0));
            return (x * x + (temp * temp) - 1);
        }
    );
}

This makes the calculation somewhat simpler in this example. In a more complicated example, statement lambdas can do a lot more than an expression lambda, which can execute only a single line of code.

Here’s a brief summary of lambda statement formats.

  • Expression lambda with one parameter:

    x => x * x
  • Expression lambda without parameter types that has multiple parameters:

    (x, y) => x * y
  • Expression lambda with parameter types:

    (float x, float y) => x * y
  • Statement lambda without parameter types that does not return a value:

    (x, y) =>
    {
        float result = x + y;
        MessageBox.Show("Result: " + result.ToString());
    }
  • Statement lambda without parameter types that returns a value:

    (x, y) =>
    {
        float temp = x + y;
        return temp * temp;
    }
  • Statement lambda with parameter types that returns a value:

    (float x, float y) =>
    {
        float temp = x + y;
        return temp * temp;
    }


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, graphics, variables and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *