How to use closures in C#


Closures are often associated with functional programming languages. Closures connect a function to its referencing environment, allowing the function to access non-local variables. In C#, closures are supported using anonymous methods, lambda expressions, and delegates.

I have discussed anonymous methods and lambda expressions in previous articles. So what’s a delegate? A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. Delegates are used to define callback methods and implement event handling.

This article talks about how we can work with closures using anonymous methods, lambda expressions, and delegates in C#. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.

We’ll use this project to illustrate the use of anonymous methods, lambdas, and delegates as closures in the subsequent sections of this article.

A closure as a first-class function in C#

A closure is defined as a first-class function containing free variables bound in the lexical environment. The C# programming language treats the first-class function as though it were a first-class data type. This means that you can assign the function to a variable, invoke it, or pass it around much the same way you work with any other first-class data type.

Copyright © 2021 IDG Communications, Inc.



Source link