Home > Tutorial for Beginners > Delegates in C#

Delegates in C#

Delegates:

Definition: Delegates adds more value to event driven programming. They are very similar to function pointer in C++. Delegates are type safe pointers and they provide callback function in safe way. They are used to declare the reference type. Delegates are used to declare custom events. If you want to change the behaviour of your application in runtime, delegates are the best example, in other words here you can apply delegates. They always work with events. Event driven programming contains two types of object:

1. Source: Knows as Events and

2. That responds to the changes, known as event Handler.

Delegates work in between of these two objects. C# delegates are class methods and they can be static. To declare a delegate you have to use delegate keywords as

Syntax

// Declare delegates

   public delegate void MyDelegate();

In above line you have declare the delegate type, now you have to associate this with a method as

public partial class Delegates : System.Web.UI.Page

{

    // Declare delegates

    public delegate int MyDelegate(int i);

 

    protected void Page_Load(object sender, EventArgs e)

    {

        // Associate delegates with method

        MyDelegate del = CallMyDelegates;

 

        //invoke

        int j = del(10);

        Response.Write("Result: " + j + "</br>");

 

    }

 

    public int CallMyDelegates(int i)

    {

        return i + 10;

    }

}

While calling delegates, make sure parameters and return type should matched with the delegates return type, otherwise they will raise an error. Like other types of .Net, delegate is a type of function method. They are used to call methods asynchronously. btn_Save_Click(object sender, EventArgs e) events are the simple example of delegates.

Delegate Types

  • Single Delegates: You can associate single method.
  • Multicast delegates: You can associate multiple method.

Also Read – Difference between Events and Delegates in C #

Post Comments Below