C# Lambda Expression

Lambda expression syntax

Lambda expressions use special syntax. They allow functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator. This separates the parameters and statement body of the anonymous function.

Based on:

.NET 4.5

Example

Lambda: programming term

This program uses lambda expressions and other anonymous functions. The source text uses the => operator. This is a syntax for separating the parameters to a method from the statements in the method's body.

Tip:Lambda expressions use the token => in an expression context. In this context, the token is not a comparison operator.

Token

The => operator can be read as "goes to" and it is always used when declaring a lambda expression. A lambda expression allows you to use a function with executable statements as a parameter, variable or field.

Methods
Program that uses lambda expressions: C#

using System;

class Program
{
    static void Main()
    {
	//
	// Use implicitly typed lambda expression.
	// ... Assign it to a Func instance.
	//
	Func<int, int> func1 = x => x + 1;
	//
	// Use lambda expression with statement body.
	//
	Func<int, int> func2 = x => { return x + 1; };
	//
	// Use formal parameters with expression body.
	//
	Func<int, int> func3 = (int x) => x + 1;
	//
	// Use parameters with a statement body.
	//
	Func<int, int> func4 = (int x) => { return x + 1; };
	//
	// Use multiple parameters.
	//
	Func<int, int, int> func5 = (x, y) => x * y;
	//
	// Use no parameters in a lambda expression.
	//
	Action func6 = () => Console.WriteLine();
	//
	// Use delegate method expression.
	//
	Func<int, int> func7 = delegate(int x) { return x + 1; };
	//
	// Use delegate expression with no parameter list.
	//
	Func<int> func8 = delegate { return 1 + 1; };
	//
	// Invoke each of the lambda expressions and delegates we created.
	// ... The methods above are executed.
	//
	Console.WriteLine(func1.Invoke(1));
	Console.WriteLine(func2.Invoke(1));
	Console.WriteLine(func3.Invoke(1));
	Console.WriteLine(func4.Invoke(1));
	Console.WriteLine(func5.Invoke(2, 2));
	func6.Invoke();
	Console.WriteLine(func7.Invoke(1));
	Console.WriteLine(func8.Invoke());
    }
}

Output

2
2
2
2
4

2
2
Generator

In the example, we see the => syntax. This can be read as "goes to." It separates the arguments from the method body of a lambda expression. It is not a comparison operator. The => syntax separates the left from the right.

Left side:This is an empty parameter list, a formal parameter list, or an implicit parameter list from the body.

Right side:This can be a statement list inside curly brackets with a return statement, or an expression.

Func1 through func8 denote anonymous function instances. The Func<TResult> type is anonymous function with one result value and no parameter. The Func<T, TResult> type is a function with one parameter and one result value.

Func

Note:The Action type indicates a function instance that does not receive a parameter and does not return a value.

ActionKeyword: keywords direct program behavior

The delegate keyword is used to denote an anonymous function in the C# language. After the delegate keyword, you can use a formal parameter list or even omit the list if there are no parameters.

And:You must specify a statement list that is executed when the anonymous function is invoked.

Finally, the program calls the methods that were all specified inside the method body. The Func generic type and the Action type have an instance method called Invoke. It receives a number of parameters that depends on the type.

Then:The method body of each of the lambdas and anonymous functions is executed.

Anonymous functions

This section provides information

The term anonymous function describes both delegates and lambda syntaxes. An anonymous function has no name and cannot be invoked with normal method lookup. For this reason, method overloading is not possible for anonymous functions.

Overload

Many experts regard lambda expressions as a complete improvement over the delegate syntax. It is sometimes advised that you use lambda expressions instead of the delegate keyword syntax when it is possible.

Anonymous Functions

Specification

The C# Programming Language: C-Sharp

The C# language specification describes anonymous function types. The annotated edition of The C# Programming Language (3rd Edition) covers all the syntaxes available. This article derives its example from the specification's.

Tip:You can find more detail on this topic using the precise technical terminology on page 314 of this book.

Performance

Performance

Do lambda expressions cause any performance problems? I benchmarked a lambda expression against an anonymous method specified with the delegate keyword. These two functions were used as arguments to the Count extension method.

BenchmarkCount

The lambda expression performed the same as the explicit Func instance. The differences in execution time were in the range of noise. We see then that lambda expressions cause no excess performance hit beyond other delegate syntaxes.

Locals used in benchmark: C#

int[] array = { 1 };
Func<int, bool> f = delegate(int x)
{
    return x == 1;
};

Lambda expression tested: C#

int c = array.Count(element => element == 1);

Delegate tested: C#

int c = array.Count(f);

Summary

Framework: NET

We looked at the syntactic rules of lambda expressions with help from the C# specification itself. We described lambda expressions with zero arguments, one argument, two arguments, and one return value.

Also:We looked at the delegate keyword when used for anonymous functions. This is a similar but more verbose syntax form.


C#: Delegate