
Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax | 95 |
In the C# example, the += syntax is for assigning a delegate to an event (using a bit of programmer slang, this syntax is commonly said to “wire up an event”). The VB example uses AddHandler and AddressOf to assign the AccountOverDraft method to the OverDraft event. In the C# example, the delegate is a new instance of EventHandler and the event is OverDraft. If you remember, the delegate type of OverDraft is Eventhandler, which defines the precise message contract.
The next piece of the puzzle is the method to be notified when the event happens. This method is the parameter given to the new EventHandler delegate instance. You saw earlier where the account_OverDraft (AccountOverDraft in VB) method had the signature specified by the EventHandler class, making it possible for our method to be specified as the new EventHandler parameter. With that one line of code (the one with the += statement), account_OverDraft (AccountOverdraft in VB) is now hooked up to the OverDraft event. This means that when the value of CurrentBalance is set to less than zero via the set accessor of CurrentBalance, the OverDraft event gets fired because the OverDraft(this, EventArgs.Empty) is called, which then invokes the account_OverDraft (AccountOverdraft in VB) method (the method we wired up to the event), which in turn executes its code.
One more note about events: you’ll see them used extensively in graphical user interface (GUI) code. Think about the GUI code that has reusable components, like buttons and list boxes. Every time the user clicks a button or selects an item in the list box, you want code to execute and do something, like perhaps save the user’s data somewhere. You do this through events: a Click event for the button and a SelectedItemChanged for the list box. This is the standard way that you program GUIs; you have an event and you define a method to hook up to that event so that your running program can do some work in reaction to the user.
Event, Delegate, and Handler Code Completion
While there isn’t a snippet, per se, to create an event or delegate, in C# there is Intellisense Code Completion support for hooking a delegate up to an event, which also generates the handler method. The process takes two steps: delegate and handler creation. To get started, type the reference to the event’s containing instance, the event name, and +=. As soon as you type the = sign, you’ll see a tooltip like the one in Figure