Concept of a Delegate in C#


Basic delegate

An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

A delegate is a form of type-safe function used by the .NET Framework.  Delegates specify a method to call and optionally an object to call the method on.

or

Shifting of work from one's control to another.
delegate is keyword to make delegates in our program.
Delegate is also work as class which has a base class Delegate (abstract class).
Delegates are used to pass methods as arguments to other methods.
In event handling its too difficult to have a person for every event differently:

fig delegate.JPG
Delegates have the following properties

  1. Delegates are similar to C++ function pointers, but are type safe.
  2. Delegates allow methods to be passed as parameters.
  3. Delegates can be used to define callback methods.
  4. Delegates can be chained together; for example, multiple methods can be called on a single event.
Syntax

public delegate <return type> DelegateName();

Program

using System;
namespace Deligate
{
    public delegate int MyfirstDeligate(int i, int j);
    public delegate void MySecondDeligate();
    class Program
    {
        public int Add(int i, int j)
        {
            return i + j;
        }
        public int Sub(int i, int j)
        {
            return i - j;
        }
        public void Show()
        {
            Console.WriteLine("MCN SOLUTION PVT LTD.");
        }
        public void Display()
        {
            Console.WriteLine("Hi");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            MyfirstDeligate m = new MyfirstDeligate(p.Add);
            int result = m(9, 5);
            m = new MyfirstDeligate(p.Sub);
            int result1 = m(50, 10);
            Console.WriteLine(result + "   " + result1);
            MySecondDeligate m2 = new MySecondDeligate(p.Show);
            MySecondDeligate m3 = new MySecondDeligate(p.Display);
            m2 = m2 + m3;
            m3 = m2 - m3;
            m2();
            m3();
            Console.Read();
       }
    }
}

 Output 

 output.gif

Up Next
    Ebook Download
    View all
    Learn
    View all