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.
- Call back
- Event handling
For creating and using delegates involve four steps
- Delegate declaration
- Delegate instantiation
- Delegate methods definition
- Delegate invocation
Modifiers
Four modifiers of the delegate type
- Public
- Private
- Protected
- Internal
Example of delegate
-
- Delegate voin Sanjibdelegate();
- Class A
- {
- Public void DispalyA()
- {
- Console.writeline(“Display A”);
- }
- }
- Class B
- {
-
- Static public void DisplayB()
- {
- Console.writeline(“Display B”);
- }
- }
-
- A mya = new A();
- Sanjibdelegate san = new Sanjibdelegate(mya.DisplayA);
-
- 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:
- The return type of the delegate must be void.
- None of the parameters of the delegate type can e declared as output parameters, using out keyword.