Delegates
This were pointer to Methods whenever we call a method to execute a method it creates a stack and destroys .Each time the method is called a stack is created and destroyed.
If u wants to call a method for multiple times without multiple stacks getting created and destroyed make use of a “Delegate”.
Is a type which holds the method(s) reference in an object?
It is also referred as type safe function. Type safe means same parameter type and same return type
Advantages
Used to call a method asynchronously.
Effective use of delegates approves the performance of application.
Declaration
Syntax:
Public delegate type of delegate, delegatename ()
Eg:
Public delegate int mydelegate(int delvar1,int delvar2)
Delegates:
Public void Add(int x, int y)
{
Console.WriteLine(x+y);
}
Public delegate void AddDel(int x, int y)
Public string SayHello(string name)
{
return “Hello” +name;
}
Public delegate string sayDel(string str)
Creating objects of Delegates
AddDel ad=new AddDel(Add);
sayDel sd=new sayDel(SayHello);
Delegates are of two types
Single cast delegates
Multi cast delegates
Single cast delegate:
If a delegate is used for calling only a single method than it is known as single cast delegate.
output
Multi cast Delegate
If a delegate is used for calling more than one method than it is called as Multi Cast Delegate.
If you want to add a method to the invocation list of a delegate object, you simple make use of the overloaded+=operator and if you want to remove a method from invocation list make use of overloaded –
Note:
If you want to create a multi cast delegate with return type you will get the return type of the last method in the invocation list.
No comments:
Post a Comment
Thank you for visiting my blog