articles

Home / DeveloperSection / Articles / Delegates

Delegates

Amit Singh 7595 19-Sep-2010

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++ 

Delegates

 Example: 

 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 = newSampleDelegate(sub);
            int sub1 = calculation(4, 5);
            Console.WriteLine("Subtraction between two value= " + sub1);
            calculation = newSampleDelegate(mul);
            int mul1 = calculation(4, 5);
            Console.WriteLine("multiplication between two value= " + mul1);
            Console.Read();
        }
        staticint add(int f, int g)
        {
            return f + g;
        }
        staticint sub(int f, int g)
        {
            return f - g;
        }
        staticint mul(int f, int g)
        {
            return f * g;
        }
    }
}

  Run the project and output: 

Delegates

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



Updated 04-Mar-2020

Leave Comment

Comments

Liked By