Delegates are references to methods. So we have used to references to object, e.g.

Employee emp = new Employee ();

Here emp is a reference to an object of the Employee class type. Hence, each reference has two properties:

1.       The type of object (class) the reference can point to.

2.       The actual object referenced (or pointed to) by the reference.

Delegates are similar to object references, but are used to reference methods instead of objects. The type of a delegate is type or signature of the method rather than class. Hence a delegate has three properties:

  •     The type or signature of the method that the delegate can point to
  •     The delegate reference which can we used to reference a method
  •     The actual method referenced by the delegate

The concept of delegates is similar to the function pointers used in C++ 



 namespace Delegate
    class Program
        delegate int SampleDelegate(int a, int b);
        static void Main(string[] args)
            SampleDelegate calculation = null;
            calculation = new SampleDelegate(add);        
            int add1 = calculation(4, 5);
            Console.WriteLine("Sample of delegate in c#");
            Console.WriteLine("Adding two value= " + add1);
            calculation = new SampleDelegate(sub);
            int sub1 = calculation(4, 5);
            Console.WriteLine("Subtraction between two value= " + sub1);
            calculation = new SampleDelegate(mul);
            int mul1 = calculation(4, 5);
            Console.WriteLine("multiplication between two value= " + mul1);
        static int add(int f, int g)
            return f + g;
        static int sub(int f, int g)
            return f - g;
        static int mul(int f, int g)
            return f * g;

  Run the project and output: 


  This is the simple example to show how we use the delegate.

  Modified On Nov-29-2017 10:45:04 PM

Leave Comment