Sunday 12 April 2015

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:-
//delegate declaration
Delegate voin Sanjibdelegate();
Class A
{
//instance delegate method
Public void DispalyA()
{
Console.writeline(“Display A”);
}
}
Class B
{
//static delegate method
Static public void DisplayB()
{
Console.writeline(“Display B”);
}
}
//delegate instance
A  mya  = new A();
Sanjibdelegate san = new Sanjibdelegate(mya.DisplayA);
//static method call here direct with class name.
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.

No comments:

Post a Comment