Closures are an interesting feature for a language. I have heard a lot of questions around how we can declare closures in C# and hence I thought to start a blog on it. Over the internet, there are lots of examples on closures available which are taking help of functional languages like F#, yes it is very important in perspective of these languages as those are easy to declare and also inherently supported yet other languages like C# or VB.NET can also take help of these feature. Lets take a look how C# can take help of closures in this post.
What is a Closure?
Closures may be defined as a set of behaviour or instructions that are encapsulated as an object such that it could be sent to other object yet can hold the context of the caller. In other words, a closures are special object that are encapsulated into an object but can hold the context of the caller.
In C# we define closures using delegates. In C# 3.0 we have language support to easily declare a delegate in a program. This widely increases the use of delegates in the program using lamda expressions. Lets put the closures in terms of some examples.
static void Main(string[] args)
{
int i = 20;
Action myAction = () => Console.WriteLine("value of i = {0}", i);
Program.RunMe(myAction);
Console.ReadLine();
}
public static void RunMe(Action myaction)
{
if(myaction != null)
myaction();
}
When you run the above code, you will find that the 20 will be printed on the screen which is run from the method RunMe. Yes, the lamda expression ensures that the instruction set which it specifies is encapsulated within a closure so that the object could be sent on any other objects. As you can see, I am using the contextual variable i from within the RunMe method, hence you can say that myAction forms a closure in C#.
Read more: DOT NET TRICKS