Author avatar

Dániel Szabó

Closures and the Lambdas

Dániel Szabó

  • Sep 16, 2019
  • 5 Min read
  • Sep 16, 2019
  • 5 Min read
Languages Frameworks and Tools


In C#, the capability that allows a method or a function to reference a non-local variable or value is called closure. This feature is commonly utilized in conjunction with the lambda functions which are nothing more than anonymous functions that developers utilize over named function to provide a way to add flexibility. This guide will make the terms of lambda functions and closures clear, and also demonstrate the capabilities of these very important features.

Non-local Variables

In C#, accessing a variable outside the scope of a function is possible and considered normal. Variables accessed this way are called non-local variables. You may also hear developers referring to this type of variable as captured variable. They refer to the same type of variable.

1class LambdasNClosure
3	static string platform = "Pluralsight";
4    static void WhoIsTheBest()
5    {
6    	Console.WriteLine($"{platform} is the best!");
7    }
8    static void Main(string[] args)
9    {
10        WhoIsTheBest();
11        Console.ReadKey();
12    }

Calling the function gives us the following results.

1Pluralsight is the best!

This demonstrated the concept called closure.

Lambda Functions

There are lots of articles about lambdas being closures and some people tend to agree that they are only part of the truth. I strengthen the camp of those in the opposition. Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.

Lambda expressions can basically take two forms.

  1. Expression lambdas
  2. Statement lambdas

Expression lambdas usually look like this:

1Func<double, double, bool> isItEqual = (x,y) => x == y;

Technically, we define the input and output types and provide an expression which is evaluated based on the argument, then it is returned as a result. Sometimes the compiler cannot infer the input types, so you may want to be on the safe side and specify them like this.

1Func<double, double, bool> isItEqual = (double x, double y) => x == y;

Statement lambdas usually look like this:

1Action<string> Welcome = name =>
3	Console.WriteLine($"Welcome {name} to the Pluralsight platform!");

Note how the closing curly brace also ends in a semicolon. When we work with statement lambdas, we usually create multiple expressions - encapsulate them inside our function. These are the best practices for creating an atomic operation; they exist for a single purpose/action.

Now we take a sharp turn and combine lambdas and closures.

1public static partial class ClosureDemo {
2	public static void Outside()
3		{
4			string notLocal = "Closure based lambda!";
5			Func<string> demo = () =>
6			{
7				string local = "This is lambda, ";
8				return local + notLocal;
9			};
10			string message = demo();
11			Console.WriteLine($"The burrowed message: {message}");
12		}   
13	}
14class LambdasNClosure
15	{
16	static void Main(string[] args)
17	{
18		ClosureDemo.Outside();
19		Console.ReadKey();
20	}

The output is as follows:

1The burrowed message: This is lambda, Closure based lambda!

In this example our non-local variable did not change, however, this situation might not always be true. If the variable changes, the referencing function will be impacted. Sometimes this is exactly the case we want to achieve. For example, we could have a function that logs the internal change in a function's state with a lambda function. That way, each change to the state will result in a different log.


Under the hood closure is nothing more than a syntactic sugar that allows access to a non-local variable. This is very convenient, however, it comes with a price. Another wording for closure which is fairly common is that it's a block of code which maintains its environment and can be called at a later point in time.

Let's demonstrate it with a tiny code.

1static void Main(string[] args)
3    int foo = 10;
4    Func<int> Bar = () => { return foo; };
5    Console.WriteLine($"Foo: {Bar()}");
6    foo = 20;
7    int fighter = Bar();
8    Console.WriteLine($"Fighter: {fighter}");

The output shows the following results:

1Foo: 10
2Fighter: 20


Closures can be underwhelming, as alone they do not seem to provide too much extra functionality or gain. Their power becomes apparent only when you combine them with libraries which take advantage of their nature. Letting you express specific behaviors at the right places. I hope this was informative for you and that you found what you were looking for.