Delegates in C#


Delegates is referred to as a type safe function pointer in C#. Which holds the reference of method with a particular argument list and return type. When you want to initiate a delegate in a program you can associated its instance with any method that are matches its signature and return type. You can call or invoke the method through the delegate instance. The syntax of the delegates are as follows:

<access specifier> delegate<return type> <DeligateName> (<data type> <argument list>);

When we initiate the delegate just same like as creating class instances such as follows:

<DeligateName> <InstanceName>=new <DeligateName>(<Methodname>);

If we are using static methods in a class then no need to create instance of class it is call to delegate instance. If you are define non static method in a class that are access via class_object.MethodName pass as an argument in creation time of delegate.  

You are also holds multiple methods in a delegate but every method return void else there is a run-time exception.  

Its major role in event design that encapsulate the method call from caller. Caller has no need to access other properties, method on the object of a class.

For example, we create a delegate named 'DeligateDemo' that are taking two arguments and we are create another delegate that are represented as a multi delegate and no argument list.


using System;
namespace DelegateEx
    //creating delegate named 'DelegateDemo'
    public delegate int DelegateDemo(int Num1, int Num2);
   public delegate void MulDelegate();
    class Program
        //Creating non static method
       public int Calculate(int Number1, int Number2)
            int res = Number1 * Number2;
            return res;
       public static void Display()
           Console.WriteLine("You are in Display Function");
       public void Show()
           Console.WriteLine("You are in show Function");
        static void Main(string[] args)
            //creating instance of Program class named 'p'.
            Program p = new Program();
            //Input two integer parameter
            Console.WriteLine("Enter the First value: ");
            int num1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the Second value: ");
            int num2 = Convert.ToInt32(Console.ReadLine());
            //Creating instance of delegate 'DelegateDemo'
            DelegateDemo obj = new DelegateDemo(p.Calculate);
            //passing values to the deligate
            int Result=obj(num1, num2);
            //Printing results
            Console.WriteLine("Multiplication :"+Result);
            //Creating multi Delegate  instance  & accesing static method
            MulDelegate obj1 = new MulDelegate(Display);
            //Calling Display via delegate instance
            //Non-static function via class object in the muldelegate
            obj1 = new MulDelegate(p.Show);




Leave Comment