Crash course: Lambda Expressions

As I have seen lambda expressions the first time, I thought to myself: “What’s that for a strange syntax?”. At first, I didn’t really understand the purpose of the source code. But after a short training time, I have not only understood the source code, but felt the lambda expression as a valuable language extension.

With this crash course I would therefore like to also give you a quick introduction to the lambda expressions. I will show you their purpose, syntax, and use based on simple examples.

 
Purpose

Lambda expressions allow to create anonymous methods. Lambda expressions are a kind of evolution of anonymous methods and allow a shorter and more readable syntax. They are needed, for example when using LINQ. Also in the context of asynchronous programming they are very helpful.

The name “lambda expression” refers to the lambda calculus, a formal language for the study of functions.

 
Syntax

Lambda expressions have the following syntax:

(Input parameters) => {Instructions}

  • => is the so called lambda-operator
  • Left of the operator are the parameters
  • Right of the operator are the instructions

 

The following guidelines should be followed when creating lambda expression. For each guideline, a corresponding example is given.

  • Any number of input parameters are possible. Input parameters are separated by comma.

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

 

  • If only one input parameter is used, then the brackets are not needed.

x => {return x + „abc“;};

 

  • The parameter types of the input parameters are determined automatically by the compiler. But they can also be explicitly specified.

(string x, string y) => {return x + y;};

 

  • If only one instruction is used, then the brackets and the return keyword are not needed.

(x, y) => x + y;

 

  • In the instruction block you should use up to three instructions at maximum because lambda expressions should be used for short methods only.

(x, y) => { string s = x + “ “ + y; return s; };

 

Example

In an introduction to a programming concept the classical “Hello World” should not be missed. Therefore the following code snippet shows the hello world example, implemented using a lambda expression.

    1 Func<string, string, string> concat = (x, y) =>

    2 {

    3     string s = x + " " + y;

    4     return s;

    5 };

    6 

    7 Console.WriteLine(concat("Hello", "World"));

 

If you look back to the previously shown syntax guidelines, then you probably already see many possibilities for optimization of the sample code. The following code snippet shows the same functionality as before, but the lambda expression was strongly reduced.

    1 Func<string, string, string> concatShort = (x, y) => x + " " + y;

    2 

    3 Console.WriteLine(concatShort("Hello", "World"));

 
Use variables of the enclosing method

Lambda expressions can use local variables of the method in which they were created. That means, they can use the external variables of the enclosing method. The following example shows a lambda expression that accesses a local variable.

    1 int outerValue = 0;

    2 Action print = () => Console.WriteLine(outerValue);

    3 

    4 outerValue = 10;

    5 print();

 

The local variable within the lambda expression is evaluated only when it is called. Therefore the output in the above-shown example is “10”.

The external variables can also be changed within the lambda expression. The following code snippet shows a function which changes the external variable.

    1 int outerValue = 0;

    2 Func<int> increment = () => outerValue++;

    3 

    4 Console.WriteLine(increment());

    5 Console.WriteLine(increment());

    6 Console.WriteLine(increment());

 

The example creates the following output:

0
1
2

 
Interestingly, the first output is “0”. That means, the WriteLine command is executed prior to the increment command. What happens if we use a postfix notation for the increment command? The following example shows the according source code. Here, the ++ command has been moved in front of the parameter to use it in postfix notation.

    1 int outerValue = 0;

    2 Func<int> increment = () => ++outerValue;

    3 

    4 Console.WriteLine(increment());

    5 Console.WriteLine(increment());

    6 Console.WriteLine(increment());

 

Now the example creates the following output:
1
2
3

 
Summary

Lambda expressions are an efficient progression of anonymous methods. The shortened syntax can generate more readable source code. Furthermore some C# language features such as LINQ are based on lambda expressions and heavily use them.

Advertisements
Dieser Beitrag wurde unter .NET, C#, Crashkurs abgelegt und mit verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s