.Net C# closures

A quick demo of a C# closure, thanks to Justin Etheredge at

http://www.codethinked.com/c-closures-explained

A closure can be defined as:

A first-class function with free variables that are bound in the lexical environment.

Here’s a good post on Stack Overflow regarding closures What are closures in .Net and another post discussing Multithreading and closures.

The example below is a simple implementation of a closure.

using System;

namespace CsharpClosure
{
    class Program
    {
        static void Main()
        {
            var hWOutput = HwFunc();
            
            Console.WriteLine(hWOutput("Hello"));
       
            Console.WriteLine(hWOutput("Hello"));

            Console.WriteLine(hWOutput("Hello"));

            Console.ReadKey();
        }

        private static Func<string, string> HwFunc()
        {
            var myVar = "";
            Func<string, string> result = input =>
                                           {
                                               myVar = myVar + " World";
                                               return input + myVar;
                                           };
            return result;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *