Lambda expressions, delegates, predicates & closures in C#

C#.NET

Please contribute by voting. Thanks!
8
Lambda expressions, delegates, predicates and closures - complicated sounding terms that in fact are easy to grasp once you actually understand what they mean and how they work...

Lambda expression

A lambda expression is an anonymous function that you construct it with the lambda operator => 

The following example will create a function that always return the integer 1:
Func<int> getOne = () => 1;
int numberOne = getOne();
//the variable numberOne will now contain 1
You can pass parameters to the function by declaring them inside the parenthesis:
Func<int, int> addOne = (a) => a + 1;
int addedNumber = addOne(3);
//the variable addedNumber will not contain 4
Should you need to write a more extensive function, you can wrap the function body with curly brackets, this is called a statement lambda:
Func<int, int> addOneAndPrint = (a) =>
{
    var returnValue = a + 1;
    Console.WriteLine(returnValue);
    return returnValue;
};
int addedNumber = addOneAndPrint(6); //the variable addedNumber will contain 7 and the function have printed 7 to the console
If you are using the extensive form of lambda expression and want to return a value, you will need to use the return statement, just like a ordinary method.

Delegate

A delegate is a type that represents a method signature (including parameter list and return value)

The following example will first create a delegate type (IntegerCalculation), it will then create a method that match the delegate's method signature (Add). When the method Calculate is called, it will first instantiate the delegate with the newly created method. Finally the delegate instantiation will get invoked (thus running the Add-method):
private delegate int IntegerCalculation(int a, int b);

private int Add(int a, int b)
{
  return a + b;
}

public void Calculate()
{
  IntegerCalculation adder = Add;
  Console.WriteLine("Thre result: " + adder(2, 4)); //Will return 6
}
Delegates can be used together with anonymous methods, i.e. the method that matches the delegate's method signature is created as we instantiate the delegate like so:
private delegate int IntegerCalculation(int a, int b);

public void Calculate()
{
  IntegerCalculation adder = delegate(int a, int b)
  {
    return a + b;
  };
  Console.WriteLine("Thre result: " + adder(2, 4)); //Will return 6
}
The anonymous method can be replaces with a lambda expression:
IntegerCalculation adder = (int a, int b) =>
{
  return a + b;
};

Predicate

A predicate is a pre-made delegate that takes a type as well as an instance of said type and returns a boolean value:
public delegate bool Predicate<in T>(T obj)
It is used for evaluate a condition and return true/false accordingly:
Predicate<int> isEven = (int a) => a % 2 == 0;
Console.WriteLine("Is 2 even: " + isEven(2));
You will often see it in Linq-statements where it is used for filter a sequence of values (the predicate is defined as a parameter to the Where-method):
var integers = new List<int> {1, 2, 3, 4, 5, 6};
var evenNumbers = integers.Where(p => p % 2 == 0);
evenNumbers.ToList().ForEach(p => Console.WriteLine(p));

Closure

In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.
var foo = 5;
Func<int> myClosure = () => { return foo; };
var bar = myClosure();

Console.WriteLine(bar);
As you can see in the example above, the foo-variable defined in the local scope is accessible to the lambda expression, thus creating a closure.

Article created: Aug 14 '15. Edited Aug 31 '15.

1 Comment

2
dolev gamzo [2]  •  Dec 7 '17  •   •  Reply

In the closure example i would add 'foo = 6;' and again show the output. Great article!

Your comment

You need to sign up / log in to comment this article

Author

Created by Robert Bengtsson [126] Aug 14 '15

Share article

Do you know about

Bootstrap?

Write an article