|
A delegate in C# language allows us to reference a method. The other way to say this delegate is a function pointer. The function pointer is same as we have pointer to an address now in this case we have pointer to a method address. There are two types of delegates :-
- Single-Cast Delegate:- Here the delegate will refer to or point to single method or we can Say that the pointer is to single method from the delegate.
- Multi-Cast Delegate:-In the multi-cast delegate, the delegate refer to or point to more than One method at runtime.
Delegates features:
- Delegate is a function pointer.
- Delegate declaration is same as method declaration, except they have delegate modifier in front of it.
- The method that a delegate refers or pointing to must have same signature as of delegate method.
- To use a delegate, we have to create the instance of the delegate and pass the method that it is pointing too or referring to.
- Invoke (), This method can be used to invoke the delegate.
The delegates can be declared by adding a delegate keyword in front of any method. For Example- delegate void Mydelegate();
Note:- This is declaration of the delegate and it specifies the method signature that it is pointing or referring. This means the signature of the method that a delegate pointing has no parameter and will not return any thing. But this is an example and we can say the delegate can refer to any type of method.
Example: Demonstrate Delegates

ClsDelegate13.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
class ClsDelegate13
{
delegate void Mydelegate ();
static String str = "" ;
static String sd = "" ;
public String singlecastfx()
{
sd = "" ;
sd = "Single Cast Delegate ==> " ;
Mydelegate d = null ;
d += new Mydelegate (singlecastdelegatefx);
d.Invoke();
sd = sd + " :: appender" ;
return sd;
}
public String multicastfx() {
str = "" ;
str = "starting Value ==> " ;
Mydelegate d = null ;
d += new Mydelegate (firstfx);
d += new Mydelegate (secondfx);
d();
str = str + " :: appender" ;
return str;
}
public void firstfx()
{
str = str + " :: firstfx" ;
}
public void secondfx()
{
str = str + " :: secondfx" ;
}
public void singlecastdelegatefx()
{
sd = sd + " ::singlecastdelegatefx" ;
}
}
}
Form13.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form13 : Form
{
public Form13()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
ClsDelegate13 objDelegate = new ClsDelegate13 ();
MessageBox .Show(objDelegate.multicastfx());
}
private void button2_Click( object sender, EventArgs e)
{
ClsDelegate13 objDelegate = new ClsDelegate13 ();
MessageBox .Show(objDelegate.singlecastfx());
}
}
}
Output:
Clicking On: Single-cast Delegate Button

Clicking On: Mutil-cast Delegate Button

|