Explain Delegates and different type of delegates in C#

 

Define Delegate

 

A delegate in C# is similar to a function pointer in C or C++. It allows the programmer to encapsulate a reference to a method (nothing but an event) inside a delegate object.

Microsoft C# Delegates have the following properties:

·         Delegates are similar to C++ function pointers, but are type safe.

·         Delegates allow methods to be passed as parameters.

·         Delegates can be used to define callback methods.

·         Delegates can be chained together; for example, multiple methods can be called on a single event.

 

Declarations:

Syntax:

<Access modifiers> delegate <datatype> delegatename() // here delegate is keyword.

Example:
 
public delegatedouble Delegate_Prod();
 

Delegate Types: Delegates are two types basically.

1. Single cast delegates:-  Single cast delegates refers  one method at a time
2. Multicast delegates:-  Multicast delegates refers more than one method.

Single Cast Delegate:

using System;

namespace Test.BasicDelegate

{

public delegate void  SingleCastDelegate(); //Delegate definition

class TestDelegate

{

    public static void MyFunc()

    {

        Console.WriteLine(“Hi, I was called by Delegate...“);

        Console.WriteLine(“*************************“);

 

    }

public static void Main(string[] args)

    {

        SingleCastDelegate ObjSC = new SingleCastDelegate (MyFunc);   //Creating the Delegate Instance

       SingleCastDelegate();       //invoking the MyFunc method       

        Console.ReadLine();

    }

}

}

OUTPUT:

 

Hi, I was called by Delegate...

*************************

 

 

 

MultiCast Delegate:

 

delegate void MulticastDelegate(int x, int y);

Class Class2

{

    static void Method1(int x, int y)

    {

        Console.WriteLine("Hi, u r in Method 1");

    }

 

    static void Method2(int x, int y)

    {

        Console.WriteLine("Hi, u r in Method 2");

    }

 

    public static void <place w:st="on" />Main</place />()

    {

        MulticastDelegate objfunc = new MulticastDelegate(Method1);

        objfunc += new MulticastDelegate (Method2);

        objfunc (10,20);             // Method1 and Method2 are called

        objfunc -= new MulticastDelegate(Method1);

        objfunc(40,50);             // Only Method2 is called

    }

}

 

 

OUTPUT:

Hi, u r in Method 1

Hi, u r in Method 2

Hi, u r in Method 2

 

Conclusion: This article would help to understand Microsoft delegates in C# using simple examples. And these delegates are especially developed by Microsoft is to create events and to change some objects ability to customize their behavior.