Follow in Twitter & Facebook


Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools


Monday, March 19, 2012

Delegates in C#.net

Delegate is an important concept in C#.net. You can also check Arraylist,Hash table,Sorted list and Dictionary C#.Net.
Delegate is implemented as an object which stores the address of another method.
Advantages of Delegates:
1-Effective use of delegate improves the performance of application
2-Used to call a method asynchronously

To work with delegates we have to follow 4 steps. These are as follows
(1)-Declare the delegate
(2)-Define the Method
(3)-Creating the instance of the delegate
(4)-Invoke the delegate

(1)-Declare the delegate
public delegate <Return type> delegate name(parameters)
Ex-
Public delegate void XYZdelegate();
(2)-Define the Method
void Display()
{

}
(3)-Creating the instance of the delegate
XYZdelegate obj1 = new XYZdelegate(<Target i.e The method name> );
(4)-Invoke the delegate
delegateobject name(<parameters>);
Lets Explain by one example
Example:
delegates demo [windows app]
Public class Form1
-----------------
-----------------
Public delegate void Sampledelegate(string s)
void Display(string s)
{
MessageBox.Show(s);
}

Private void btninvoke-click(-,-)
{
Sampledelegate obj1 = new Sampledelegate(Display);
obj1("delegates are simillar to function pointer");
}
}

Applications Of Delegates:
Basically two important applications are there for delegates. Thease are
1-Event handling
2-Generic Routines

1-Event handling:
To work with event handling in .net framework, Microsoft providing set of delegates.
Every delegate will maintain the address of corresponding Event Procedure.

2-Generic Routines
Delegate is also useful in case Generic Routines.

Besides this simple delegate also Multicast delegate is also there

Multicast Delegate:

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

You can also check What is the difference between AcessSpecifier and Acessmodifier in C#.Net ?




0 on: "Delegates in C#.net"