What are Closures in CSharp ?

closures in C#

What are Closures in CSharp ?

By questioning as: What closures are in C# ? We have to look the benefits of using these closures in our C# development environment.

To put it very simply, closures allow you to encapsulate some behaviour, pass it around like any other object, and still have access to the context in which they were first declared. This allows you to separate out control structures, logical operators etc from the details of how they’re going to be used. The ability to access the original context is what separates closures from normal objects, although closure implementations typically achieve this using normal objects and compiler trickery.

It’s easiest to look at a lot of the benefits (and implementations) of closures with an example. I’ll use a single example for most of the rest of this article. I’ll show the code in Java and C# (of different versions) to illustrate different approaches. All the code is also available for download so you can tinker with it.

reference:http://csharpindepth.com/articles/chapter5/closures.aspx

Difference between Closure and Lambda function

Lambda functions are just a form of anonymous functions which are defined by no name.
A closure function can access those variables that are not in its parameter list.
Closures are not something very powerful.
We can made a robust code without even using them.
They can make the code quite easier to implement and understand. That is the best quality about using a closure.

In C#, we can made closures with the help of both anonymous methods as well as delegates. It relies upon .NET framework version that we currently are using.

Here is the simple example:

using System;
using System.Collections.Generic;

namespace ClosuresExamples
{
class Program
{

/* static Action closure declared as delegate
Action keyword encapsulates a method that has no parameter
* and no return type
*/
static Action myClosure = delegate
{
string str1= “Hello”;
string str2=” Dude!”;
Console.WriteLine(“{0}”, str1+str2);
Console.ReadKey();
};

static void Main(string[] args)
{
/* this closure can be called like and normal method without
* parameters and return types*/
myClosure();

}

}
}

Output:
Hello Dude!

Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.