Shiman’s Weblog

Collecting stones from the sea-shore.

C# .Net Delegates : Arrays of Delegates

Arrays of delegates can be the impetus of elegant solutions that would otherwise be unavailable. Creating an array of delegates is the same as creating an array of any type. Selecting from a set of tasks at run time is an example of when an array of delegates is essential to an elegant solution. The switch statement is one solution, in which each case of the switch statement is assigned to a task. Suppose that there are about three lines of code associated with each task. In the next revision of the application, 30 additional tasks are added, which results in an additional 90 lines of code. This solution provides linear growth and is not particularly scalable. With an array of delegates, regardless of the number of tasks, the solution is one line of code. Now and in the future, this solution remains one line of code. This solution is more scalable than the switch statement approach. In the following code, an array of delegates facilitates invoking a task from a menu of choices:

using System;

 

namespace Examples.Delegates

{

    public delegate void Task();

 

    public class Program

    {

        public static void Main()

        {

            // array of delegates

            Task[] tasks = { MethodA, MethodB, MethodC };

            string resp;

            do

            {

                Console.WriteLine(“TaskA – 1″);

                Console.WriteLine(“TaskB – 2″);

                Console.WriteLine(“TaskC – 3″);

                Console.WriteLine(“Exit – x”);

                resp = Console.ReadLine();

                if (resp.ToUpper() == “X”)

                {

                    break;

                }

                try

                {

                    int choice = int.Parse(resp) – 1;

                    // as promised, one line of code to invoke

                    // the correct method.

                    tasks[choice]();

                }

                catch

                {

                    Console.WriteLine(“Invalid choice”);

                }

            } while (true);

        }

 

        public static void MethodA()

        {

            Console.WriteLine(“Doing TaskA”);

        }

 

        public static void MethodB()

        {

            Console.WriteLine(“Doing TaskB”);

        }

 

        public static void MethodC()

        {

            Console.WriteLine(“Doing TaskC”);

        }

    }

}

 

August 15, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | 2 Comments