Delegates
This is the new concept introduced in C#.
Def: A delegate is the reference to the method. Using the delegate, you can call the method. This is used in "GUI Events" and "Multi-Threading" concept in future.
Implementation Syntax:Def: A delegate is the reference to the method. Using the delegate, you can call the method. This is used in "GUI Events" and "Multi-Threading" concept in future.
- Define the Method:
accessmodifier returntype methodname(arguments)
{
//some code
}
- Declare the delegate (as a data member):
delegate returntype delegatename(arguments);
- Create instance of the delegate:
delegatename delegateinstancename = new delegatename(methodname);
- Access the properties of the delegate:
delegateinstancename.Target
//gets the class name that contains the target method
delegateinstancename.Method
//gets the signature of the target method
- Invoke / call the target method:
delegateinstancename.Invoke();
(or)
delegateinstancename.Invoke(arguments);
Download above code for Demo on Delegates : Download Links
Multi Cast Delegates
- It contains the address of multiple methods.
- You can add the reference of the methods, one by one using ―+=‖ operator.
- When you call the methods using ―Invoke()‖ method, all the methods will be called at-atime.
Limitation: If there is any return value, you can get only the last returned value.
No comments:
Post a Comment