Thursday, November 27, 2008

How to create an array of functions in C#?

This was a question tapping my head recently. Also I was wondering how could we achieve creating pointer of functions in C#. Well that lead me to a small experiment on it and figured out some interesting results as expected.  The answer was possible through C# delegates.
First of all we need to understand what C# delegates are. Well to put it simple as I searched the net for a simple explanation, and found a quite simple explanation on CodeProject: "Delegates are simply function pointers". Well to make it more clear, with delegates you can create links to various functions. Ofcourse the description given in the above CodeProject link is fairly enough to understand the use of it. 
To put it simple, you can define a common method definition for various functions that have a similar pattern of method definition. Ex: If you have functions to add, subtract, multiply and divide two numbers, the most popular way is to have a method definition with the unique name and two parameters. The pattern would be:
 
[public|private] int <methodname> (int x, int y)

During system design if you know this pattern in advance then you could define this pattern withe use of a delegate like this:

delegate int delWithTwoParameters(int x,int y);

Here the delWithTwoParameters is the delegate identifier. During run time we can dynamically bind the methods to this delegate and call the appropriate function. Basically all methods will be called from a single (delegate)source. But there are many more like type safety, secure bla bla...But that is not my consideration here... :) Sorry.
Here is a piece of code I did today, which explains the use of delegates and how to create an array of functions based on a single delegate which is the problem of this discussion...Here I have explained the usage of how to use a normal function and a static function with the same delegate:

using System;
using System.Text;
using System.Reflection;

namespace TestConsole
{
    //Everything is under this class
    class Program
    {
        //A normal Method
        public void callHelp(string name)
        {
            Console.WriteLine("{0}...! Please help me\n", name);
        }
        
        //A Static void method
        public static void DisplayGreeting(string name)
        {
            Console.WriteLine("Hey {0}, please come here...!",name);
        }

   //Declaration of the pointer to a function with string as it's parameter
        delegate void delWithStringPar(string var);
        
        static void Main(string[] args)
        {   //Creating an Object instance of Program class to be able to call the normal "callHelp" method
            Program prog = new Program();
            
            //The list of names
            string [] Names = {"Mafaz","Lahiru","Chatura"};
            //Creating the Delegate (function) array from the System 
   //namespace and setting the value to the maximum number of Instances
            
            //Array for the static DisplayGreeting function
            Delegate[] delGreet = new Delegate[Names.Length];
            
            //Array for the normal callHelp function
            Delegate[] delHelp = new Delegate[Names.Length];
            
            //A counter to iterate through elements
            int i = 0;
                foreach (string name in Names)
        
    delGreet[i]= new delWithStringPar(Program.DisplayGreeting);
              delHelp[i]= new delWithStringPar(prog.callHelp);

          //cast the delegate arrays to the preferred Delegate
                    ((delWithStringPar)delGreet[i])(name);
                    ((delWithStringPar)delHelp[i++])(name);

              //Note: The "i" is incremented by one to advance
     //to the next index.Even if you don't increment the
     //consecutive delegate instance replaces the previous.
                }          

            //Waiting for user input to exit screen
            Console.ReadLine();
        }
    }
}

No comments: