What is Delegate?
- Delegate is one of the base types in .NET. Delegate is a class, which is used to create and invoke delegates at runtime.
- A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. Delegate is very special type of object as earlier the entire the object we used to defined contained data but delegate just contains the details of a method.
Advantage Of Delegate
In simple words delegates are object oriented and type-safe and very secure as they ensure that the signature of the method being called is correct. Delegates makes event handling simple and easy.
Example
namespace ConsoleApp3
{
delegate void calculator(int n); //Declare Deligates
class DelegateExamples
{
static int number = 0;
public static void add(int n)
{
number = n + n;
Console.WriteLine("Addition - {0}", number);
}
public static void mul(int n)
{
number = n * n;
Console.WriteLine("Multiplication - {0}", number);
}
public static void Main()
{
calculator c1 = new calculator(add);//instantiating delegate
calculator c2 = new calculator(mul);
c1(50);//calling method using delegate
c2(100);
Console.ReadLine();
}
}
}
Output:
Addition - 100
Multiplication - 10000
No comments:
Post a Comment
Please let me know if you have any feedback or doubts.