Popular Posts

There was an error in this gadget

Oct 6, 2012

Purpose of Delegate And Captured variable in C#.




Demonstrate a captured variable.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DemoCapture
{
    // This delegate returns int and takes an int argument. 
    delegate int CountIt(int end);
    class VarCapture
    {
        static CountIt counter()
        {
            int sum = 0;

            // Here, a summation of the count is stored 
            // in the captured variable sum. 
            CountIt ctObj = delegate(int end)
            {
                for (int i = 0; i <= end; i++)
                {
                    Console.WriteLine(i);
                    sum += i;
                }
                return sum;
            };
            return ctObj;
        }

        class Program
        {
            static void Main(string[] args)
            {
                // Get a counter 
                CountIt count = counter();

                int result;

                result = count(3);
                Console.WriteLine("Summation of 3 is " + result);
                Console.WriteLine();

                result = count(5);
                Console.WriteLine("Summation of 5 is " + result);
                Console.ReadKey();
            }
        }
    }
}



Purpose of Delegate

- It supports event programming
- It gives the program a way to execute a method at runtime without having to know
precisely what that method is at compile time.





No comments:

Post a Comment