What is Delegates and how to create it in C#

What is Delegates and how to create it in C#?

The dictionary meaning of delegate is a person acting for another person. In c# it really means method acting for another method.

Definition of delegate

A delegate is a class type object that contains the details of a method rather than data. It used to invoke a method that has been encapsulated into it at the time of its creation. Delegate in c# are used for two purposes.

An important feature of a delegate is that it can be used to hold reference to a method to any class. The only requirement is that its signature must match the signature of the method.

  1. Call back
  2. Event handling

For creating and using delegates involve four steps

  1. Delegate declaration
  2. Delegate instantiation
  3. Delegate methods definition
  4. Delegate invocation

Modifiers

Four modifiers of the delegate type

  • Public
  • Private
  • Protected
  • Internal

Example of delegate

  1. //delegate declaration  
  2. Delegate voin Sanjibdelegate();  
  3. Class A  
  4. {   //instance delegate method  
  5.     Public void DispalyA()  
  6.     {  
  7.         Console.writeline(“Display A”);  
  8.     }  
  9. }  
  10. Class B  
  11. {  
  12.     //static delegate method  
  13.     Static public void DisplayB()  
  14.     {  
  15.         Console.writeline(“Display B”);  
  16.     }  
  17. }  
  18. //delegate instance  
  19. A mya = new A();  
  20. Sanjibdelegate san = new Sanjibdelegate(mya.DisplayA);  
  21. //static method call here direct with class name.  
  22. Sanjibdelegate del = new Sanjibdelegate(B.DisplayB);  
What are Multicast delegates ?

Multicast delegate is a method that holds and invokes multiple methods. It also called as combinable delegates.

It must satisfy the following conditions:

  1. The return type of the delegate must be void.
  2. None of the parameters of the delegate type can e declared as output parameters, using out keyword.
Ebook Download
View all
FileInfo in C#
Read by 9.7k people
Download Now!
Learn
View all