When we create a delegate, we are creating an object that can hold a reference to a method. Furthermore, the method can be called through this reference. Thus, a delegate can invoke the method to which it refers.
The principal advantage of a delegate is that it allows us to specify a call to a method, but the method actually invoked is determined at runtime, not at compile time.
Some Key Points:
-
Delegates can be declared either outside a class definition or as part of a class through the use of the delegate keyword.
-
Delegates have two parts : the delegate declaration and the delegate instance or static method.
-
If an exception is thrown, the delegate stops processing methods in the invocation list. It does not matter whether or not an exception handler is present.
-
The keyword delegate and the .NET infrastructure provided by the System.Delegate (all delegate types are derived) and System.Delegate.MulticastDelegate classes.
-
Delegates are the heart of event handling in .NET.
-
It is a compile-time error for the same modifier to appear multiple times in a delegate declaration.
-
Delegate types are implicitly sealed.
(A). Simple Delegate
Declaration of delegate:
delegate-modifier delegate return-type delegate-name(parameters)
Implementation of delegate:
Delegate-name delegate-object=new Delegate-name(method of class)
Illustration with an Example:
using System;
namespace SimpleDelegate
{
public
delegate int
AddNumber(int
i, int j);//declaration
of deletgate
public
class
ImplementDelegate
{
public
int Add(int
i, int j)
{
return i + j;
}
}
class
Program
{
static
void Main(string[]
args)
{
int sum = 0;
ImplementDelegate objimp = new
ImplementDelegate();//instance
of delegate
AddNumber d = new
AddNumber(objimp.Add);//implement
of delegate
sum = d(12, 13);
Console.WriteLine("Addition
of 12 and 13 is " + sum);
Console.Read();
}
}
}

Join the conversation! Your thoughts help the community grow.