Lesson 4: Implementing Delegates and Events

Lesson 4: Implementing Delegates and Events

Events are messages that indicate a noteworthy occurrence in another part of the application. When an event is raised, other parts of your application are given an opportunity to respond by executing methods called event handlers. In Chapter 2, you learned how to use Visual Studio .NET to write handlers for events raised by forms and controls. In this lesson, you will learn how to declare and raise your own events, write event handlers for those events, and dynamically add and remove event handlers at run time.

After this lesson, you will be able to

  • Explain what a delegate is and how to create one

  • Describe how to declare and raise events from your application

  • Explain how to implement event handlers and associate them with events

  • Describe how to dynamically add and remove event handlers at run time

Estimated lesson time: 30 minutes

Events are members of your class. An event represents a message that is sent to other parts of the application. When a noteworthy activity occurs in the application, your application can raise the event, which sends out the message. The event can wrap any arguments that contain information about the event and send them along with the event. Other parts of the application handle the event, which means that a method is executed in response to the event. Any method that handles an event must have the same signature as the event itself; that is, it must take the same kinds of arguments as the event passes. An event can be handled by more than one method, and a single method can handle more than one event.

Delegates

Special classes called delegates are central to how events work. A delegate is essentially a type-safe function pointer. It allows you to pass a reference to the entry point for a method and invoke that method without making an explicit method call. When you declare a delegate, you specify the signature of the method that it can call and the return type. The following example demonstrates how to declare a delegate:

Visual Basic .NET

Public Delegate Function myDelegate(ByVal D As Double) As Integer

Visual C#

public delegate int myDelegate(double D);

This example declares a delegate called myDelegate that can be used to invoke methods that return an integer and take a double as a parameter. To make use of the delegate, you must create a new instance that specifies the method to be called. In Visual Basic .NET, you use the AddressOf operator to create a reference to the address of the method. In Visual C#, you specify the method by name. For example:

Visual Basic .NET

' This method is the target for the delegate Public Function ReturnInt(ByVal d As Double) As Integer ' Method implementation omitted End Function ' This line creates an instance of the myDelegate delegate that ' specifies ReturnInt Dim aDelegate As New myDelegate(addressof ReturnInt)

Visual C#

// This method is the target for the delegate public int ReturnInt(double D) { // Method implementation omitted } // This line creates an instance of the myDelegate delegate that // specifies ReturnInt public void amethod() { myDelegate aDelegate = new myDelegate(ReturnInt); }

In Visual C#, if you create a delegate to an instance method, you must also initialize the delegate within a method. Delegates to static methods can be initialized outside a method.

Once declared and assigned, you can use the delegate to invoke the method in the same manner you would make a function call, which is shown as follows:

Visual Basic .NET

aDelegate(12345)

Visual C#

aDelegate(12345);

To create and invoke a delegate

  1. Declare the delegate, and provide a signature identical to the signature of the methods you want to invoke.

  2. Create an instance of the delegate that points to a method that has the appropriate signature.

  3. Invoke the delegate by referencing its name.

Declaring and Raising Events

As you learned in Chapter 2, forms and controls have built-in member events that are raised when events occur. For example, the Click event is raised when a user clicks a button. You can declare member events for your classes that can be raised when appropriate.

Declaring events is directly tied to delegates. In Visual C#, you must explicitly designate the delegate type that your event will use. Visual Basic .NET provides much of this functionality behind the scenes you only need to supply the name of the event and the signature of the method it requires. A default delegate matching this signature is created.

To declare an event with Visual Basic .NET

Use the Event keyword to declare an event. Supply a signature that represents the signature of the type of method that you would like to handle the event. You can use any access modifiers, such as Public, Private, or Protected. For example:

Visual Basic .NET

Public Event CalculationComplete(ByVal Total As Double)

To declare an event with Visual C#

Use the Event keyword to declare an event. Supply the type of delegate that the event will use. You can use any access modifiers, such as public, private, or protected. For example:

Visual C#

public delegate void calculationDelegate(double d); public event calculationDelegate CalculationComplete;

Once an event is declared, you can raise it in code when the designated event occurs. For example, you might have a component that represents a bank account, which could raise an Overdrawn event whenever the balance falls below zero.

To raise an event in Visual Basic .NET

Use the RaiseEvent keyword to raise the event, calling the event by name. Enclose any required parameters in parentheses. An example of the appropriate syntax follows:

Visual Basic .NET

RaiseEvent CalculationComplete(66532)

To raise an event in Visual C#

Events in Visual C# are raised by calling them by name as you would a method. Any required parameters should be enclosed in parentheses. An example follows:

Visual C#

CalculationComplete(66532);

Implementing Event Handlers

Once an event is declared, it must be associated with one or more event handlers before it can be raised. An event handler is a method that is called through a delegate when an event is raised. You must create associations between events and event handlers to achieve your desired results. If you attempt to raise an event in Visual Basic .NET that has no event handlers associated with it, nothing will happen. If you raise an event that has no event handlers in Visual C#, an error will result.

Like other members, there are instance events and Shared (static) events. Creating an event handler for an instance event requires that an association be made between a method and an object event. The object must be declared to create the event handler association. Shared (static) events, however, belong to the class itself rather than to any one instance of a class. To create an event handler for those events, you do not need to declare an instance of the class beforehand.

Event Handlers in Visual Basic .NET

In Visual Basic .NET, event handlers must be Subs and cannot return a value. You can associate a Sub with a given event by using the AddHandler keyword. AddHandler allows you to specify an event and designate a pointer to the method with which that event will be associated. The pointer is created using the AddressOf operator. An example follows:

Visual Basic .NET

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _ System.EventArgs) AddHandler myEvent, AddressOf myHandler End Sub

The AddHandler keyword cannot be used declaratively; it must be used inside a method. Thus, the association between the event and the event handler does not exist before the application s execution; rather, it is added at run time. For event handler associations that exist for the lifetime of the object, the AddHandler keyword should be placed in the class s constructor.

Visual Basic .NET also allows you to create event handler associations at design time using the Handles clause. To use the Handles clause, the object must be declared with the WithEvents keyword. The WithEvents keyword informs the containing object that it will be receiving events from the contained object.

You use the Handles clause by adding it to the end of your method declaration and specifying the object event that you are handling. For example:

Visual Basic .NET

Public Sub DisplayResults() Handles Account.CalculationComplete ' Implementation omitted End Sub

Event Handlers in Visual C#

Unlike in Visual Basic .NET, event handlers in Visual C# can return a value, and that value can be assigned to a variable in the same manner as a function call. You associate a method with a given event by creating a new instance of the appropriate delegate, which specifies the appropriate method and uses the += operator to make the association. You also can use the += operator to associate an event with an instance of a delegate that already exists. For example:

Visual C#

// These examples assume the existence of a method called // DisplayResults that has the appropriate signature for // CalculationDelegate // Creates a new delegate to create the association Account.CalculationComplete += new calculationDelegate(DisplayResults); // Creates an association with an existing delegate calculationDelegate calc = new calculationDelegate(DisplayResults); Account.CalculationComplete += calc;

Default delegates are provided for the events of the controls and classes of the .NET Framework base class library. If you want to manually add an event handler for one of these events, you do not need to declare a new delegate. Rather, you can create a new instance of the predefined default delegate. For example, the delegate class that is used for events for most of the controls in the System.Windows.Forms namespace is System.EventHandler. The following example demonstrates how to designate an event handler for the Click event of a control named button1:

Visual C#

button1.Click += new System.EventHandler(clickHandler);

Unlike Visual Basic .NET, Visual C# has no mechanism for creating event handler associations declaratively.

To handle an event in Visual Basic .NET

  • Use the AddHandler keyword to create an association between an event and a method to handle that event. The AddressOf operator allows you to receive a pointer to the appropriate method. Event handlers must have the same signature as the event being handled.

  • Alternatively, you can use the Handles keyword to associate a method with an event at design time. The method must be a member method of an object that was declared with the WithEvents keyword.

To handle an event in Visual C#

Create an instance of the appropriate delegate for the event that specified the method that will handle the event, and use the += operator to associate the event with the delegate.

Event Handlers That Handle Multiple Events

You can create event handlers that handle multiple events. For example, you might want to do this when you have more than one instance of a class or control that raises the same events. For example, you might have a group of buttons on a form that share a similar role in the application. You might create a single method to handle the Click event for all of these buttons and distinguish between them by using the sender parameter.

Associating multiple events with a single handler is simple. You use the AddHandler or += operator in exactly the same way in which you would add a single event handler. For example:

Visual Basic .NET

' Assumes the existence of a method called ClickHandler with the ' correct signature to receive button click events AddHandler Button1.Click, AddressOf ClickHandler AddHandler Button2.Click, AddressOf ClickHandler

Visual C#

// Assumes the existence of a method called ClickHandler with the // correct signature to receive button click events button1.Click += new System.EventHandler(ClickHandler); button2.Click += new System.EventHandler(ClickHandler);

In Visual Basic .NET, you can also use the Handles clause to associate multiple events with a single event handler. To create multiple associations, create a Handles clause and add multiple events separated by commas. The following example demonstrates this approach:

Visual Basic .NET

Private Sub ClickHandler (ByVal sender As System.Object, e As _ System.EventArgs) Handles Button1.Click, Button2.Click, _ Button3.Click ' Implementation omitted End Sub

Events with Multiple Handlers

An event can be handled by more than one event handler. When an event is handled by more than one handler, all the methods handling that event are executed. The order in which the methods execute is the same as the order in which the association was created. Thus, if event x is associated in code with handlers y, z, and q (in that order), when the event is raised, the order of handler execution will be y, z, and q. In Visual C#, if you return a value with your event, it will be the value of the last method executed.

To associate an event with multiple handlers, all you have to do is create an association between the event and each handler. In Visual Basic .NET, you can use the Handles clause to declaratively associate several methods with an event. If this approach is used, the order of method execution is less predictable and should be tested to learn whether it will have an effect on the dynamics of the application.

Removing Handlers at Run Time

You already learned how to dynamically add event handlers. The AddHandler keyword in Visual Basic .NET and the += operator in Visual C# can be used to dynamically create associations between events and methods. You also can remove event handler associations at run time. For example, suppose you have a class that models a bank account that raises a NotSufficientFunds event every time the account owner tries to submit a check for an amount greater than the account balance. You might associate this event with two methods: a ChargeAccount method, which assesses a fee for writing a Non-Sufficient Funds (NSF) check, and a Notify method, which notifies the account owner that the account is overdrawn. You would call the ChargeAccount method every time an NSF check was passed, but it would be redundant to call the Notify method more than once before the account balance became positive. In this case, you could remove the event handler for the Notify method and reinsert it when the account balance returned to the positive side.

The method by which you remove an event handler is similar to the method by which you add one. In Visual Basic. NET, you use the RemoveHandler method to disassociate an event from a delegate obtained with the AddressOf operator. In Visual C#, you use the -= operator to dynamically remove an association between an event and a method. This operator requires a reference to a delegate of the appropriate signature, and it must reference the method to be removed. The following code demonstrates how to remove the association between the Account.CalculationComplete event and the DisplayResults method:

Visual Basic .NET

RemoveHandler Account.CalculationComplete, AddressOf DisplayResults

Visual C#

Account.CalculationComplete = new calculationDelegate(DisplayResults);

Lesson Summary

  • Events are members of classes that are used to communicate interesting occurrences between classes. An instance of a class can raise a member event to send out the message. The event can be handled by methods that are designated as event handlers. These methods execute when the event is raised.

  • Delegates provide the functionality behind events. A delegate is a strongly typed function pointer. It can be used to invoke a method without making an explicit call to that method. The creation of associations between events and event handlers requires the use of delegates. In Visual Basic .NET, the role of the delegate is largely behind the scenes, whereas in Visual C#, it is more explicit.

  • Events are declared as members of the class. In Visual Basic .NET, only the event need be declared, but in Visual C#, the event must reference an appropriate delegate. A member event is raised by using the RaiseEvent statement in Visual Basic .NET or by calling the event by name in Visual C#. Events in Visual Basic .NET cannot return a value, but events in Visual C# can return a value.

  • Methods that handle events are called event handlers. You can create associations between events and event handlers in code. In Visual Basic .NET, the AddHandler keyword creates an association between an event and a method represented by a delegate obtained with the AddressOf operator. In Visual C#, the event handler is created by using the += operator to associate a delegate with the event. In Visual Basic .NET, you can also use the Handles clause to create event handler associations declaratively.

  • Events can have multiple event handlers associated with them, and multiple events can be handled by the same method. Event handlers can be removed dynamically.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net