[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use statement lambdas in C#

[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 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.