
94Microsoft Visual Studio 2010: A Beginner’s Guide
Delegates
Delegates let you hook up methods as the receiver to specific events. The delegate specifies the allowable signature, the number of arguments, and their types, of a method that is allowed to be hooked up to the event as a listener or handler. The EventHandler delegate type for the OverDraft event specifies what the signature of a method should be, as follows:
C#:
public event EventHandler OverDraft;
VB:
Public Event OverDraft As EventHandler
This EventHandler is a class that belongs to the .NET Framework class library, and it, by definition, specifies that any methods hooked up to the OverDraft event must define two parameters: an object of any type and an EventArgs class. EventHandler also specifies that the method does not return a value explicitly. The following method, account_ OverDraft (AccountOverdraft in VB), matches the predefined EventHandler signature:
C#:
static void account_OverDraft(object sender, EventArgs e)
{
Console.WriteLine("Overdraft Occurred");
}
VB :
Public Sub AccountOverdraft(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("Overdraft Occurred") End Sub
Notice that the C# account_OverDraft (AccountOverdraft in VB) doesn’t return a value and has two parameters that are type object and EventArgs, respectively. The account_OverDraft (AccountOverdraft in VB) method is hooked up to the OverDraft event in the Main method in Listing
C#:
account.OverDraft += new EventHandler(account_OverDraft); account.CurrentBalance =
VB:
AddHandler OverDraft, AddressOf AccountOverdraft CurrentBalance =