Monday, 19 February 2018

What are Delegates in C#

A delegate in C# can be conpared to a function pointer in C and C++. It allows programmers to specify what the funtion to be called will look like without having to specify the particular function.



A delegate is a reference type variable that hods th reference to a function, which can change at runtime.
Delegates are very useful when programing UI controles where events have to be implemented for callbacks.

Normal Function Call Without Delegate
In normal function call, we specify the function to be called directly. So if a funciton is defined an a class named SomeClass and has a function called Do(), then the function can be called using the syntax:
SomeFunction.Do()


namespace DelegateDemo
{
    public class SomeClass
    {
        public void Process()
        {
            Console.WriteLine("Process() begin");
            Console.WriteLine("Process() end");
        }
    }

    public class Test
    {
        static void Main(string[] args)
        {
            SomeClass myClass = new SomeClass();
            myClass.Process();
        }
    }
}


The above code works perfectly in most situaition. However, there may be sometimes when we dont' want to call  a function directly. We need to pass it to some ohter method to call it. This would be neccessary  in an event driven system sucha s a graphical user interface applicaiton. In this case we would like some code to be executed when a user clicks on a button, or when I want to log some informaiton but cannot at the moment specify how it would be logged.

Three Steps to Using a Delegate
Step 1: Declaration
Step 2: Instantiation
Step 3: Invocation


Declaring Delegates in C#
Declaration of delegates determines that methods that can be referenced by the delegate. For a delegate to refer to a function, the function must have the signature of that delegate.

Consider the example:
public delegate int SomeDelegate (string );

The delegate declare above can be used to reference any function that has a single string parameter and returns an int type variable.
The syntax for delegate declaration is :

delegate return-type identifier ([parameters]);

where:
return-type: The return type  which has to be the same as the return type of the function
identifier: Name of the delegate
parameters: The parameters to the function

Instatiating Delegates
After a delegate have been declared, a delegate object msut be created with the new keyword and be associated with the a particular method. When creating a delegate, the argument passed to the new expression is written similar to a function call, but without arguments to the function.
For example:

public delegate void writeString(string s);

writeString d1 = new writeString(ToScreen);
writeString d2 = new writeString(ToFile);

In the above example, a delegate called writeString() is delared that takes a single string.
The we instantiate two delegates d1 and d2 using 

The function below illustrates how to delare, instantiate and use delegates to reference functions that take int values and returns int values.


    class Program
    {
        static int num = 10;
        delegate int NumDelegate(int n); //DECLARE A DELEGATE NumDelegage
        public static int Add(int val1)
        {
            num = num + val1;
            return num;
        }
        public static int Mult(int val2)
        {
            num = num + val2;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
        static void Main(string[] args)
        {
            //CREATE THREE NEW DELEGATE INSTANCES
            NumDelegate nd;
            NumDelegate nd1 = new NumDelegate(Add);
            NumDelegate nd2 = new NumDelegate(Mult);
 
            nd = nd1;  //nd1 PERFORMES Add(5) GIVING 15
            nd = nd + nd2; //nd2 PERFORMS Mult(10) GIVIN 50

            //MULTICASTING (EXPLAINED BELOW)
            nd(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }

In the above code, a delegate is created called NumDelegate that would point to a method that takes an integer parameter.
In the main program, three delegates are instantiated nd, nd1 and nd2.
At the end of the program the output would be 65.
Part 2: Multicast