A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Types of Delegates.
1. Single cast delegate
2. Multi cast Delegate
3. Generic Delegate
- Action
- Func
- Predicate
Why Delegates?
Delegates are used in the following cases:
Delegates can be used to handle(call/invoke) multiple methods on a single event.
Delegates can be used to define callback(asynchronous) methods.
Delegates can be used for decoupling and implementing generic behaviors.
Delegates can be invoked method at runtime.
Delegates can be used in LINQ for parsing the ExpressionTree.
Delegates can be used in different Design Pattern.
==============================================================
Func, Action and Predicate are generic inbuilt delegates present in System namespace.
All three can be used with method, anonymous method and lambda expression.
Func can contains 0 to 16 input parameters and must have one return type.
Action can contain 1 to 16 input parameters and does not have any return type.
Predicate delegate should satisfy some criteria of method and must have one input parameter and one Boolean return type either true or false.
Input parameters of custom delegates is fixed but Func and Actions input parameter is variable from 0 to 16 and 1 to 16 respectively.
Example:
public delegate void DelTest(string str);
public class SampleA
{
public void SampleAA(string st)
{
Console.WriteLine(st);
}
public void MethodB(string stt)
{
Console.WriteLine(stt);
}
public static void SampleC()
{
Console.WriteLine("MethodC");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a1 = new SampleA();
// DelTest DelA = SampleA.SampleC;
DelTest d1 = new DelTest(a1.SampleAA);// Single Cast
d1 += new DelTest(a1.MethodB);//Multicast
d1("Mike");
Console.ReadKey();
}
}
Where to use
A Delegate can be used in various ways depending on the requirements of the project. The following are the lists of areas where a delegate can be used to provide better output and enhance the performance of the application.
Method Invocation (using delegate instance)
Event Handling using delegate
Callback and asynchronous implementation
Multiple method calls using Multicast delegate
Conclusion
A normal delegate or a Multicast delegate is a very powerful feature in C# and it can be used by developers in various scenarios for more flexibility and a better way to improve the performance of the application.
No comments:
Post a Comment