Delegates
- It is a reference type, holds address of a method.
- Allows to change reference to a method at runtime.
- Referring method should have the return type and function signature same as that of the delegate.
- The following are the steps for implementing Delegates
o
Declare a delegate
*
Syntax
[access modifier] delegate
<return type> <delegate name> <parameter list>
*
E.g.
public delegate void MyDelegate();
*
This delegate can refer any method having no
parameter with no return type.
o
Instantiate a delegate
*
MyDelegate
delObj = new MyDelegate(staticMethod);
*
delObj is an object of type MyDelegate
*
delObj refers to staticMethod, by passing the
name of method to the delegate constructor.
o
Invoke a delegate
*
Delegates are invoked using its object name and
passing the parameters, if required, in a similar way of calling methods.
*
delObj();
- Types of Delegate
o
Single-cast
Delegate
*
Refers to only one method at a time.
o
Multicast
Delegate
*
A single delegate can refer to multiple methods.
*
Contains an invocation list of multiple methods.
*
Invokes multiple methods provided all methods
have same return type and same function signature.
*
When invoked, executes the referenced methods in
the calling order.
DOWNLOAD SAMPLE CODE: CLICK HERE
DOWNLOAD SAMPLE CODE: CLICK HERE
0 comments:
Post a Comment