Delegates in C#
1) Delegate is a kind of function pointer as we have in C or C++.
2) It holds the reference to a method.
3) Reference to a method can be changed at run-time.
4) We can add or remove reference to method using += and -= respectively.
5) It is used to implement events and callbacks.
6) It can refer to any method having same signature as that of delegate itself.
7) Effective use lead to performance improvements throughout the application.
Example
delegate double MyMethod(int a, int b); // Declaration of delegate
class Area
{
public static double Rectangle(int l, int b) // Same signature like delegate's
{
return l*b;
}
public static double Triangle(int b, int h) // Same signature like delegate's
{
return (0.5*b*h);
}
}
class Program
{
static void Main(string[] args)
{
MyMethod methodArea = Area.Rectangle;
Console.WriteLine("Area is -:"+ methodArea(10, 5)); // It will call Rectangle.
methodArea += Area.Triangle;
Console.WriteLine("Area is -:" + methodArea(10, 5)); // It will call Triangle.
methodArea -= Area.Triangle;
Console.WriteLine("Area is -:" + methodArea(10, 5)); // It will call Rectangle.
Console.ReadKey();
}
}
0 Comment(s)