I came from vb.net background. In c#, I come to know the word 'delegate'
Previously I was using event hadelers for that. I think it possible in c# also
so why do we need delegate?
I have searched in google a lot but still problem is there
If any one knows the answer Plz reply
Thank u in advance
AlanPosted Feb 27, 2008, 2:48 PM
Both C# and VB.Net have the same concepts of delegates and events. However, VB.Net (usually) handles events in a different way to C#.
In VB.Net all you need to do to wire up an event to a particular method is to declare the control as WithEvents and then append a Handles clause to the method which is to be called when the event fires. For example, if you add a button to a form:
Private WithEvents Button1 As Button
Private InitializeComponent()
Me.Button1 = New Button
' other code
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Code to handle event
End Sub
However, C# doesn't have either the WithEvents or Handles keywords. Instead you just declare the control normally and then wire up the event using a delegate:
private Button button1;
private InitializeComponent()
{
this.button1 = new Button();
this.button1.Click += new System.EventHandler(this.button1_Click);
// other code
}
private void button1_Click(object sender, System.EventArgs e)
{
// Code to handle event
}
A delegate can be thought of as a method pointer (similar to a function pointer in C) though, if it's an instance method, it also includes a reference to the object on which the method is to be called. Moreover, delegates can be 'multicast' which means they can call several methods one after the other by adding those methods to their invocation list.
An event is itself a type of delegate and, to wire up the event, you use C#'s special syntax to add a new delegate, pointing to the handler method, to the event's invocation list.
Of course, when you use Visual Studio, all this code is added automatically for you by the designer.
It's also possible in VB.Net to wire up events manually using the AddHandler statement. For example:
AddHandler Me.Button1.Click, AddressOf Me.Button1_Click
In this case you should not use the WithEvents or Handles keywords as well.