C# Closures

C# Closures Tutorial

Advertisements

Closures  allows to use variables from outside the scope of action and store values of the variables in memory in order to reuse them later.  A closure in C# takes the form of an in-line delegate. You can find more about lambda expressions in my post about it here.  A closure is attached to its parent method meaning that variables defined in parent’s method body can be referenced from within the anonymous method. It will make more sense after analysing the example.

In this post I’ll be using Action delegate, if you are not familiar with the concept of delegates and events. Click on the links. If you know the basics let’s move on.

 

To demonstrate this concept I’ll be using slightly modified example given by Jamie King 

class Program
{
  static void Main(string[] args)
  {
     Action a = MyAction();
     Action b = MyAction();
     a(); a(); a();
     b(); b();

     Console.ReadLine();
//Output will be 
// 1 2 3
// 1 2
  }
  static Action MyAction()
  {
     Action ret = null;
    int i = 0;
    ret += () =>
    {
       i++;
    };
    ret += () =>;
    {
       Console.WriteLine("Action i= " +i);
    };
    return ret;
  }
}

This is great way of demonstrating how closures works. We create a static method that contains int i, and returns an action. To demonstrate and example of chaining i created two lambda expressions, one for incrementing the i value and one for printing the variable. This method is called multiple times inside the main method.

Two different actions can refer to the same i variable and have different outcomes. It’s because each time we create new action and we call this method C# is creating a class in the background, class that stores the values that is using. This way we can refer to the value from the original scope and with new copies of action we have different values. This is syntax sugar added in later version of C#. This was just vary simple illustration of the concept of courses. In the next post I’ll cover more practical, real word examples. Stay Awesome!

 

Author: indiedevart

Indie Games Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s