Delegates
Delegates
What is Delegates ?
• A delegate is an object which refers to a method or you can say it is a
reference type variable that can hold a reference to the methods.
• Singlecast delegate
– Singlecast delegate point to single method at a time.
• Syntax:
– [modifier] delegate [return_type] [delegate_name]
([parameter_list]);
• modifier: It is the required modifier which defines the access
of delegate and it is optional to use.
• Syntax
– [delegate_name] [instance_name] = new [delegate_name]
(calling_method_name);
Example Single Delegate
using System; public static int getNumber()
//declaring delegate {
delegate int Calculator(int n); return number;
public class DelegateExample }
{ public static void Main()
static int number = 100; { // instantiating delegate
Calculator c1 = new Calculator(add);
public static int add(int n)
Calculator c2 = new Calculator(mul);
{
/ /calling method using delegate
number = number + n; c1(20);
return number; Console.WriteLine("After c1 delegate, Number
} is: " + getNumber());
public static int mul(int n) c2(3);
Console.WriteLine("After c2 delegate, Number
{
is: " + getNumber());
number = number * n;
return number; }
} }
Multicasting of a Delegate
• Multicasting is a delegate which holds the reference of more
than one method.
using System;
public delegate void DelEventHandler();
class Program
{
public static event DelEventHandler add;
static void Main(string[] args)
{
add += new DelEventHandler(USA);
add += new DelEventHandler(India);
add += new DelEventHandler(England);
add();
}
static void USA()
{ Console.WriteLine("Hello USA"); }
static void India()
{ Console.WriteLine("Hello India"); }
static void England()
{ Console.WriteLine("Hello England"); }
}
Example 2
using System; class Demo1
public delegate void Hello(); {
class Demo static void Handler()
{ {
public event Hello e1; Console.WriteLine("Helllo");
public void OnEvent() }
{ public static void Main()
if(e1!=null) {
e1(); Demo d1=new Demo();
else d1.e1+=Handler;
Console.WriteLine("Not Register...."); d1.OnEvent();
} }
} }