Before reading this article, please go through the following articles:
DelegatesDear reader, today we will discuss another important component of OOP, which is delegates. It's the modern approach to call methods. Using that approach you can call any method with the same signature as the delegate. So we can say that a delegate is the launching pad for methods; any method can be launched that matches the pattern. Or a Delegate is a class. When you create an instance of it, you pass in the function name (as a parameter for the delegate's constructor) to which this delegate will refer.In simple words, a delegate is a type that safely encapsulates a method; a delegate is a pointer to a method. Just like you can pass a variable by reference, you can pass a reference to a method. Delegates are often used to implement callbacks and event listeners. A delegate does not need to know anything about the classes or methods it works with.A Delegate consists of the following three parts:
Simple Example 1:Output:Block A:
Block B:
Block C:
EventsA hook on an object where the code outside of the object can say "When that something happens, that fires this event, please call my code".Simple Example 2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace @event
{
public partial class Form1 : Form
{
public int a=1;
public Form1()
{
InitializeComponent();
this.button1.Click += new System.EventHandler(this.button1_Click);
}
private void button1_Click(object sender, EventArgs e)
MessageBox.Show(a.ToString());
a++;
}
}
Output:In the preceding example we have defined the simple event on button click. When we click the button once, it will display the message box three times or call the click event three times.Delegate and EventsThe best uses of delegates are in the events and we have daily use delegates with events without knowing them.Simple Example 3:Output:Block A:
View All