Delegate are similar to pointer in c/C++ to function. It is reference type variable that holds the references to the method. It can contain references of many method and that can be called when we need. It does not have method body. It is object oriented and safe. Delegate are function pointer that is used to reference a method.  A Function that is added to delegate should have the same return type and signature.

Delegate in c sharp

In the real world example we can say that we act according to the situation. Talking about delegate it does the same thing. In the above diagram there are three functions and it will be called according to the situation or need. 

Multicasting Delegate

It is a extension of Normal delegate

Delegate can be combine

+ is use for adding method when we are using delegate

-   Is use for subtracting

It follow FIFO fisrt in first out.               

It can be created using Delegate keyword. It has three steps




Declaration of Delegate

  delegate void MyDelegate(string s); 

now we take an simple example to understand delegate 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
    delegate void MyDelegate(string s);
    class Program
        public static void Hello(string s)
            Console.WriteLine("  Hello, {0}!", s);
        public static void Mindstick(string s)
            Console.WriteLine("Hello Mindstick, {0}!", s);
        static void Main(string[] args)
            MyDelegate a, b, c, d;
            // Create the delegate object a that references
            // the method Hello:
            a = new MyDelegate(Hello);
            // Create the delegate object b that references
            // the method Goodbye:
            b = new MyDelegate(Mindstick);
            // The two delegates, a and b, are composed to form c:
            c = a + b;
            // Remove a from the composed delegate, leaving d,
            // which calls only the method Mindstick:
            d = c - a;
            Console.WriteLine("Invoking delegate a:");
            Console.WriteLine("Invoking delegate b:");
            Console.WriteLine("Invoking delegate c:");
            Console.WriteLine("Invoking delegate d:");



Delegate in c sharp

  Modified On Mar-17-2018 04:32:05 AM

Leave Comment