Use statement lambdas in C#

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 a complicated expression lambdas, the code can use a "statement lambda." A statement lambda contains any number of statements inside braces. If a statement lambda must return a value, it must use a return statement just as a method would. like expression lambdas, a statement lambda 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, the statement lambda 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 with multiple parameters and no parameter types
    (x, y) => x * y
  • Expression lambda with parameter types
    (float x, float y) => x * y
  • Statement lambda that does not return a value without parameter types
    (x, y) =>
    {
        float result = x + y;
        MessageBox.Show("Result: " + result.ToString());
    }
  • Statement lambda that returns a value without parameter types
    (x, y) =>
    {
        float temp = x + y;
        return temp * temp;
    }
  • Statement lambda that returns a value with parameter types
    (float x, float y) =>
    {
        float temp = x + y;
        return temp * temp;
    }

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.