blog

Home / DeveloperSection / Blogs / Delegate in c sharp

Delegate in c sharp

Simond Gear1462 20-Feb-2017

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

1-Declaration

2-Initialization

3-Calling

Declaration of Delegate

  delegatevoidMyDelegate(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
{
    delegatevoidMyDelegate(string s);
    classProgram
    {
        publicstaticvoid Hello(string s)
        {
            Console.WriteLine("  Hello, {0}!", s);
        }
 
        publicstaticvoid Mindstick(string s)
        {
            Console.WriteLine("Hello Mindstick, {0}!", s);
        }
        staticvoid Main(string[] args)
        {
            MyDelegate a, b, c, d;
 
            // Create the delegate object a that references
            // the method Hello:
            a = newMyDelegate(Hello);
            // Create the delegate object b that references
            // the method Goodbye:
            b = newMyDelegate(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:");
            a("A");
            Console.WriteLine("Invoking delegate b:");
            b("B");
            Console.WriteLine("Invoking delegate c:");
            c("C");
            Console.WriteLine("Invoking delegate d:");
            d("D");
        }
    }
}

 

Output

Delegate in c sharp


Updated 17-Mar-2018

Leave Comment

Comments

Liked By