Delegates using examples
Delegate is a form of type safe functional pointer. in compile time we don't know which method will be invoked. We can invoke a delegate asynchronous. Mostly it will be used in event drive programming. number of parameter, type of parameters and return type of a delegate should be match with method signature.
Delegate is a form of type safe functional pointer. in compile time we don't know which method will be invoked. We can invoke a delegate asynchronous. Mostly it will be used in event drive programming. number of parameter, type of parameters and return type of a delegate should be match with method signature.
There are three steps in defining and using delegates:
Declaration
Instantiation
Invocation
delegate
========
Declaration:
delegate void simpledelegate();
public void simplefun()
{
......
}
Instantiation:
simpledelegate sd = new simpledelegate(simplefunc);
Invocation:
sd();
Event is based on publishing and subscribing concept.
declare an event ( in user control)
================
public delegate void RefreshTreeHandler();
public event RefreshTreeHandler refreshtree;
protected void OnRefreshTree()
{
if(refreshtree != null)
{
refreshtree();
}
}
publishing an event in usercontrol
==================================
this.OnRefreshTree();
Subscribing an event
====================
objusercontrol.refreshtree += new usercontrol.refreshtreehandler(method);
Delegates holds address of one or more methods.
These are used to hide information like class names and method names.
Delegates are used to create user defined events on fly as we needed in our code.
Delegates are of two types
1.Single cast delegate
2.Multi caste delegate
Sample code:
Multicaste delegate Example: