Creating Classes

Using objects is fairly straightforward and intuitive. It is the kind of thing that even the most novice programmers pick up and accept rapidly.

Basic Classes

As discussed earlier, objects are merely instances of a specific template (a class). The class contains the code that defines the behavior of its objects, and defines the instance variables that will contain the object's individual data.

Classes are created using the Class keyword, and include definitions (declaration) and implementations (code) for the variables, methods, properties, and events that make up the class. Each object created based on this class will have the same methods, properties, and events, and its own set of data defined by the fields in the class.

The Class Keyword

If you want to create a class that represents a person — a Person class — you could use the Class keyword:

Public Class Person
   ' Implementation code goes here
End Class

As you know, Visual Basic projects are composed of a set of files with the .vb extension. It is possible for each file to contain multiple classes, which means that within a single file you could have something like this:

Public Class Adult
  ' Implementation code goes here.
End Class
        
Public Class Senior
  ' Implementation code goes here.
End Class
        
Public Class Child
  ' Implementation code goes here.
End Class

The most common and preferred approach is to have a single class per file. This is because the Visual Studio 2012 Solution Explorer and the code-editing environment are tailored to make it easy to navigate from file to file to find code. To demonstrate why, choose the Project ⇒ Add Class menu option to add a new class module to the project, and call it People.vb. Next add in the various classes shown in the preceding snippet. When you create a single class file with all these classes, the Solution Explorer simply displays a single entry, as shown in Figure 3.12. However, with Visual Studio 2012, you can now expand that single entry and see the reference to the four different classes defined within that single file.

Figure 3.12 Placing multiple classes in a single file

3.12

This chapter uses one class per file in the examples, as this is the most common approach. Returning to the project again access the Project ⇒ Add Class menu option to add a new class module to the project. You'll be presented with the standard Add New Item dialog. Change the name to Person.vb and click Add. The result will be the following code, which defines the Person class:

Public Class Person
        
End Class

With the Person class created, you are ready to start adding code to declare the interface, implement the behaviors, and declare the instance variables.

Fields

Fields are variables declared in the class. They will be available to each individual object when the application is run. Each object gets its own set of data — basically, each object gets its own copy of the fields.

Earlier, you learned that a class is simply a template from which you create specific objects. Variables that you define within the class are also simply templates — and each object gets its own copy of those variables in which to store its data.

Declaring member variables is as easy as declaring variables within the Class block structure. Add the following code to the Person class:

Public Class Person
        
   Private mName As String
   Private mBirthDate As Date
End Class

You can control the scope of the fields with the following keywords:

  • Private—Available only to code within the class
  • Friend—Available only to code within the project/component
  • Protected—Available only to classes that inherit from the class (discussed in detail in Chapter 4)
  • Protected Friend—Available to code within your project/component and classes that inherit from the class whether in the project or not (discussed in detail in Chapter 4)
  • Public—Available to code outside the class and to any projects that reference the assembly

Typically, fields are declared using the Private keyword, making them available only to code within each instance of the class. Choosing any other option should be done with great care, because all the other options allow code outside the class to directly interact with the variable, meaning that the value could be changed and your code would never know that a change took place.


Note
One common exception to making fields Private is to use the Protected keyword, discussed in Chapter 4.

Methods

Objects typically need to provide services (or functions) that can be called when working with the object. Using their own data or data passed as parameters to the method, they manipulate information to yield a result or perform an action.

Methods declared as Public, Friend, or Protected in scope define the interface of the class. Methods that are Private in scope are available to the code only within the class itself, and can be used to provide structure and organization to code. As discussed earlier, the actual code within each method is called an implementation, while the declaration of the method itself is what defines the interface.

Methods are simply routines that are coded within the class to implement the services you want to provide to the users of an object. Some methods return values or provide information to the calling code. These are called interrogative methods. Others, called imperative methods, just perform an action and return nothing to the calling code.

In Visual Basic, methods are implemented using Sub (for imperative methods) or Function (for interrogative methods) routines within the class module that defines the object. Sub routines may accept parameters, but they do not return any result value when they are complete. Function routines can also accept parameters, and they always generate a result value that can be used by the calling code.

A method declared with the Sub keyword is merely one that returns no value. Add the following code to the Person class:

Public Sub Walk()
        
  ' implementation code goes here
        
End Sub

The Walk method presumably contains some code that performs some useful work when called but has no result value to return when it is complete. To make use of this method, you might write code such as this:

Dim myPerson As New Person()
myPerson.Walk()

Methods That Return Values

If you have a method that does generate some value that should be returned, you need to use the Function keyword:

Public Function Age() As Integer
  Return CInt(DateDiff(DateInterval.Year, mBirthDate, Now()))
End Function

Note that you must indicate the data type of the return value when you declare a function. This example returns the calculated age as a result of the method. You can return any value of the appropriate data type by using the Return keyword.

Optionally Visual Basic still allows you to return the value without using the Return keyword. Setting the value of the function name itself tells Visual Basic that this value should be used for the return:

Public Function Age() As Integer
    Age = CInt(DateDiff(DateInterval.Year, mBirthDate, Now()))
End Function

Indicating Method Scope

Adding the appropriate keyword in front of the method declaration indicates the scope:

Public Sub Walk()

This indicates that Walk is a public method and thus is available to code outside the class and even outside the current project. Any application that references the assembly can use this method. Being public, this method becomes part of the object's interface.

The Private keyword indicates that a method is available only to the code within your particular class:

Private Function Age() As Integer

Private methods are very useful to help organize complex code within each class. Sometimes the methods contain very lengthy and complex code. In order to make this code more understandable, you may choose to break it up into several smaller routines, having the main method call these routines in the proper order. Moreover, you can use these routines from several places within the class, so by making them separate methods, you enable reuse of the code. These subroutines should never be called by code outside the object, so you make them Private.

Method Parameters

You will often want to pass information into a method as you call it. This information is provided via parameters to the method. For instance, in the Person class, you may want the Walk method to track the distance the person walks over time. In such a case, the Walk method would need to know how far the person is to walk each time the method is called. The following code is a full version Person class (code file: Person.vb):

Public Class Person
  Private mName As String
  Private mBirthDate As Date
  Private mTotalDistance As Integer
  Public Sub Walk(ByVal distance As Integer)
     mTotalDistance += distance
  End Sub
  Public Function Age() As Integer
    Return CInt(DateDiff(DateInterval.Year, mBirthDate, Now()))
  End Function
End Class

With this implementation, a Person object sums all of the distances walked over time. Each time the Walk method is called, the calling code must pass an Integer value, indicating the distance to be walked. The code to call this method would be similar to the following:

Dim myPerson As New Person()
myPerson.Walk(42)

Properties

The .NET environment provides for a specialized type of method called a property. A property is a method specifically designed for setting and retrieving data values. For instance, you declared a variable in the Person class to contain a name, so the Person class may include code to allow that name to be set and retrieved. This can be done using regular methods (code file: Person.vb):

Public Sub SetName(ByVal name As String)
  mName = name
End Sub
        
Public Function GetName() As String
  Return mName
End Function

Using methods like these, you write code to interact with the object:

Dim myPerson As New Person()
        
myPerson.SetName("Jones")
Messagebox.Show(myPerson.GetName())

While this is perfectly acceptable, it is not as nice as it could be with the use of a property. A Property style method consolidates the setting and retrieving of a value into a single structure, and makes the code within the class smoother overall. You can rewrite these two methods into a single property. The Property method is declared with both a scope and a data type. You could add the following code to the Person class (code file: Person.vb):

Public Property Name() As String
  Get
     Return mName
  End Get
  Set(ByVal Value As String)
   mName = Value
  End Set
End Property

However the preceding code can be written in a much simpler way:

Public Property Name() As String

This style of defining a property actually creates a hidden backing field called something similar to _Name, which is not defined in the source code but generated by the compiler. For most properties where you are not calculating a value during the get or set, this is the easiest way to define it.

By using a property method instead, you can make the client code much more readable:

Dim myPerson As New Person()
        
myPerson.Name = "Jones"
Messagebox.Show(myPerson.Name)

The return data type of the Name property is String. A property can return virtually any data type appropriate for the nature of the value. In this regard, a property is very similar to a method declared using the Function keyword.

By default, the parameter is named Value, but you can change the parameter name to something else, as shown here:

Set(ByVal NewName As String)
   mName = NewName
End Set

In many cases, you can apply business rules or other logic within this routine to ensure that the new value is appropriate before you actually update the data within the object. It is also possible to restrict the Get or Set block to be narrower in scope than the scope of the property itself. For instance, you may want to allow any code to retrieve the property value, but only allow other code in your project to alter the value. In this case, you can restrict the scope of the Set block to Private, while the Property itself is scoped as Public(code file: Person.vb):

   Public Property Name() As String
     Get
       Return mName
     End Get
     Private Set(ByVal Value As String)
       mName = Value
     End Set
  End Property

The new scope must be more restrictive than the scope of the property itself, and either the Get or Set block can be restricted, but not both. The one you do not restrict uses the scope of the Property method.

Parameterized Properties

The Name property you created is an example of a single-value property. You can also create property arrays or parameterized properties. These properties reflect a range, or an array, of values. For example, people often have several phone numbers. You might implement a PhoneNumber property as a parameterized property, storing not only phone numbers, but also a description of each number. To retrieve a specific phone number you would write code such as the following (code file: Person.vb):

Dim myPerson As New Person()
        
Dim homePhone As String
homePhone = myPerson.Phone("home")

To add or change a phone number, you'd write the following code:

myPerson.Phone("work") = "555-9876"

Not only are you retrieving and updating a phone number property, you are also updating a specific phone number. This implies a couple of things. First, you can no longer use a simple variable to hold the phone number, as you are now storing a list of numbers and their associated names. Second, you have effectively added a parameter to your property. You are actually passing the name of the phone number as a parameter on each property call.

To store the list of phone numbers, you can use the Hashtable class. The Hashtable is very a standard object, but it allows you to test for the existence of a specific element. Add the following declarations to the Person class (code file: Person.vb):

Public Class Person
  Public Property Name As String
  Public Property BirthDate As Date
  Public Property TotalDistance As Integer
  Public Property Phones As New Hashtable

You can implement the Phone property by adding the following code to the Person class (code file: Person.vb):

Public Property Phone(ByVal location As String) As String
  Get
    Return CStr(Phones.Item(Location))
  End Get
  Set(ByVal Value As String)
    If Phones.ContainsKey(location) Then
      Phones.Item(location) = Value
    Else
      Phones.Add(location, Value)
    End If
  End Set
End Property

The declaration of the Property method itself is a bit different from what you have seen:

Public Property Phone(ByVal location As String) As String

In particular, you have added a parameter, location, to the property itself. This parameter will act as the index into the list of phone numbers, and must be provided when either setting or retrieving phone number values.

Because the location parameter is declared at the Property level, it is available to all code within the property, including both the Get and Set blocks. Within your Get block, you use the location parameter to select the appropriate phone number to return from the Hashtable:

Get
    If Phones.ContainsKey(Location) Then
        Return Phones.Item(Location)
    End If
    Return ""
End Get

In this case, you are using the ContainsKey method of Hashtable to determine whether the phone number already exists in the list. When a value exists for a location you return it; however, if no value is stored matching the location, then you return Nothing. Similarly in the Set block that follows, you use the location to update or add the appropriate element in the Hashtable. If a location is already associated with a value, then you simply update the value in the list; otherwise, you add a new element to the list for the value (code file: Person.vb):

Set(ByVal Value As String)
  If Phones.ContainsKey(location) Then
    Phones.Item(location) = Value
  Else
    Phones.Add(location, Value)
  End If
End Set

This way, you are able to add or update a specific phone number entry based on the parameter passed by the calling code.

Read-Only Properties

Sometimes you may want a property to be read-only so that it cannot be changed. In the Person class, for instance, you may have a read-write property, BirthDate, and a read-only property, Age. If so, the BirthDate property is a normal property, as follows (code file: Person.vb):

Public Property BirthDate() As Date

The Age value, conversely, is a derived value based on BirthDate. This is not a value that should ever be directly altered, so it is a perfect candidate for read-only status.

You could create all your objects without any Property routines at all, just using methods for all interactions with the objects. However, Property routines are obviously attributes of an object, whereas a Function might be an attribute or a method. By implementing all attributes as Properties, using the ReadOnly or WriteOnly attributes as necessary, and having any interrogative methods as Function routines, you create more readable and understandable code.

To make a property read-only, use the ReadOnly keyword and only implement the Get block:

Public ReadOnly Property Age() As Integer
  Get
    Return CInt(DateDiff(DateInterval.Year, BirthDate, Now()))
  End Get
End Property

Because the property is read-only, you will get a syntax error also known as a compile time error if you attempt to implement a Set block.

Write-Only Properties

As with read-only properties, sometimes a property should be write-only, whereby the value can be changed but not retrieved.

Many people have allergies, so perhaps the Person object should have some understanding of the ambient allergens in the area. This is not a property that should be read from the Person object, as allergens come from the environment, rather than from the person, but it is data that the Person object needs in order to function properly. Add the following variable declaration to the class (code file: Person.vb):

Public WriteOnly Property AmbientAllergens() As Integer
  Set(ByVal Value As Integer)
    mAllergens = Value
  End Set
End Property

To create a write-only property, use the WriteOnly keyword and only implement a Set block in the code. Because the property is write-only, you will get a syntax error if you try to implement a Get block.

The Default Property

Objects can implement a default property, which can be used to simplify the use of an object at times by making it appear as if the object has a native value. A good example of this behavior is the Collection object, which has a default property called Item that returns the value of a specific item, allowing you to write the following:

Dim mData As New HashTable()
        
Return mData(index)

Default properties must be parameterized properties. A property without a parameter cannot be marked as the default. Your Person class has a parameterized property — the Phone property you built earlier. You can make this the default property by using the Default keyword (code file: Person.vb):

   Default Public Property Phone(ByVal location As String) As String
     Get
       If Phones.ContainsKey(Location) Then
           Return Phones.Item(Location)
       End If
       Return ""
     End Get
     Set(ByVal Value As String)
       If mPhones.ContainsKey(location) Then
         mPhones.Item(location) = Value
       Else
         mPhones.Add(location, Value)
       End If
     End Set
  End Property

Prior to this change, you would have needed code such as the following to use the Phone property:

Dim myPerson As New Person()
        
MyPerson.Phone("home") = "555-1234"

Now, with the property marked as Default, you can simplify the code:

        
myPerson("home") = "555-1234"

As you can see, the reference to the property name Phone is not needed. By picking appropriate default properties, you can potentially make the use of objects more intuitive.

Events

Both methods and properties enable you to write code that interacts with your objects by invoking specific functionality as needed. It is often useful for objects to provide notification, as certain activities occur during processing. You see examples of this all the time with controls, where a button indicates that it was clicked via a Click event, or a text box indicates that its contents have been changed via the TextChanged event.

Objects can raise events of their own, providing a powerful and easily implemented mechanism by which objects can notify client code of important activities or events. In Visual Basic, events are provided using the standard .NET mechanism of delegates; but before discussing delegates, let's explore how to work with events in Visual Basic.

Handling Events

You are used to seeing code in a form to handle the Click event of a button, such as the following code:

   Private Sub Button1_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles Button1.Click
         
  End Sub

Typically, you write your code in this type of routine without paying a lot of attention to the code created by the Visual Studio IDE. However, take a second look at that code, which contains some important things to note.

First, notice the use of the Handles keyword. This keyword specifically indicates that this method will be handling the Click event from the Button1 control. Of course, a control is just an object, so what is indicated here is that this method will be handling the Click event from the Button1 object.

Second, notice that the method accepts two parameters. The Button control class defines these parameters. It turns out that any method that accepts two parameters with these data types can be used to handle the Click event. For instance, you could create a new method to handle the event (code file: MainWindow.vb):

Private Sub MyClickMethod(ByVal s As System.Object, _
    ByVal args As System.EventArgs) Handles Button1.Click
        
End Sub

Even though you have changed the method name and the names of the parameters, you are still accepting parameters of the same data types, and you still have the Handles clause to indicate that this method handles the event.

Handling Multiple Events

The Handles keyword offers even more flexibility. Not only can the method name be anything you choose, a single method can handle multiple events if you desire. Again, the only requirement is that the method and all the events being raised must have the same parameter list.


Note
This explains why all the standard events raised by the .NET system class library have exactly two parameters—the sender and an EventArgs object. Being so generic makes it possible to write very generic and powerful event handlers that can accept virtually any event raised by the class library.

One common scenario where this is useful is when you have multiple instances of an object that raises events, such as two buttons on a form (code file: MainWindow.vb):

Private Sub MyClickMethod(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles Button1.Click, Button2.Click
        
End Sub

Notice that the Handles clause has been modified so that it has a comma-separated list of events to handle. Either event will cause the method to run, providing a central location for handling these events.

The WithEvents Keyword

The WithEvents keyword tells Visual Basic that you want to handle any events raised by the object within the code:

Friend WithEvents Button1 As System.Windows.Forms.Button

The WithEvents keyword makes any event from an object available for use, whereas the Handles keyword is used to link specific events to the methods so that you can receive and handle them. This is true not only for controls on forms, but also for any objects that you create.

The WithEvents keyword cannot be used to declare a variable of a type that does not raise events. In other words, if the Button class did not contain code to raise events, you would get a syntax error when you attempted to declare the variable using the WithEvents keyword.

The compiler can tell which classes will and will not raise events by examining their interface. Any class that will be raising an event has that event declared as part of its interface. In Visual Basic, this means that you will have used the Event keyword to declare at least one event as part of the interface for the class.

Raising Events

Your objects can raise events just like a control, and the code using the object can receive these events by using the WithEvents and Handles keywords. Before you can raise an event from your object, however, you need to declare the event within the class by using the Event keyword.

In the Person class, for instance, you may want to raise an event anytime the Walk method is called. If you call this event Walked, you can add the following declaration to the Person class (code file: Person.vb):

Public Class Person
  Private msName As String
  Private mBirthDate As Date
  Private mTotalDistance As Integer
  Private mPhones As New Hashtable()
  Private mAllergens As Integer
  Public Event Walked()

Events can also have parameters, values that are provided to the code receiving the event. A typical button's Click event receives two parameters, for instance. In the Walked method, perhaps you want to also indicate the total distance that has been walked. You can do this by changing the event declaration:

  Public Event Walked(ByVal distance As Integer)

Now that the event is declared, you can raise that event within the code where appropriate. In this case, you'll raise it within the Walk method, so anytime a Person object is instructed to walk, it fires an event indicating the total distance walked. Make the following change to the Walk method (code file: Person.vb):

Public Sub Walk(ByVal distance As Integer)
   TotalDistance += distance
   RaiseEvent Walked(TotalDistance)
End Sub

The RaiseEvent keyword is used to raise the actual event. Because the event requires a parameter, that value is passed within parentheses and is delivered to any recipient that handles the event.

In fact, the RaiseEvent statement causes the event to be delivered to all code that has the object declared using the WithEvents keyword with a Handles clause for this event, or any code that has used the AddHandler method. The AddHandler method is discussed shortly.

If more than one method will be receiving the event, then the event is delivered to each recipient one at a time. By default, the order of delivery is not defined—meaning you can't predict the order in which the recipients receive the event—but the event is delivered to all handlers. Note that this is a serial, synchronous process. The event is delivered to one handler at a time, and it is not delivered to the next handler until the current handler is complete. Once you call the RaiseEvent method, the event is delivered to all listeners one after another until it is complete; there is no way for you to intervene and stop the process in the middle.

Declaring and Raising Custom Events

As just noted, by default you have no control over how events are raised. You can overcome this limitation by using a more explicit form of declaration for the event itself. Rather than use the simple Event keyword, you can declare a custom event. This is for more advanced scenarios, as it requires you to provide the implementation for the event itself.

The concept of delegates is covered in detail later in this chapter, but it is necessary to look at them briefly here in order to declare a custom event. Note that creating a fully customized event handler is an advanced concept, and the sample code shown in this section is not part of the sample. This section goes beyond what you would normally look to implement in a typical business class.

A delegate is a definition of a method signature. When you declare an event, Visual Basic defines a delegate for the event behind the scenes based on the signature of the event. The Walked event, for instance, has a delegate like the following:

Public Delegate Sub WalkedEventHandler(ByVal distance As Integer)

Notice how this code declares a “method” that accepts an Integer and has no return value. This is exactly what you defined for the event. Normally, you do not write this bit of code, because Visual Basic does it automatically, but if you want to declare a custom event, then you need to manually declare the event delegate.

You also need to declare within the class a variable where you can keep track of any code that is listening for, or handling, the event. It turns out that you can tap into the prebuilt functionality of delegates for this purpose. By declaring the WalkedEventHandler delegate, you have defined a data type that automatically tracks event handlers, so you can declare the variable like this:

Private mWalkedHandlers As WalkedEventHandler

You can use the preceding variable to store and raise the event within the custom event declaration:

   Public Custom Event Walked As WalkedEventHandler
     AddHandler(ByVal value As WalkedEventHandler)
       mWalkedHandlers = _
         CType([Delegate].Combine(mWalkedHandlers, value), WalkedEventHandler)
     End AddHandler
         
     RemoveHandler(ByVal value As WalkedEventHandler)
       mWalkedHandlers = _
         CType([Delegate].Remove(mWalkedHandlers, value), WalkedEventHandler)
     End RemoveHandler
         
     RaiseEvent(ByVal distance As Integer)
       If mWalkedHandlers IsNot Nothing Then
         mWalkedHandlers.Invoke(distance)
       End If
     End RaiseEvent
  End Event

In this case, you have used the Custom Event key phrase, rather than just Event to declare the event. A Custom Event declaration is a block structure with three subblocks: AddHandler, RemoveHandler, and RaiseEvent.

The AddHandler block is called anytime a new handler wants to receive the event. The parameter passed to this block is a reference to the method that will be handling the event. It is up to you to store the reference to that method, which you can do however you choose. In this implementation, you are storing it within the delegate variable, just like the default implementation provided by Visual Basic.

The RemoveHandler block is called anytime a handler wants to stop receiving your event. The parameter passed to this block is a reference to the method that was handling the event. It is up to you to remove the reference to the method, which you can do however you choose. In this implementation, you are replicating the default behavior by having the delegate variable remove the element.

Finally, the RaiseEvent block is called anytime the event is raised. Typically, it is invoked when code within the class uses the RaiseEvent statement. The parameters passed to this block must match the parameters declared by the delegate for the event. It is up to you to go through the list of methods that are handling the event and call each of those methods. In the example shown here, you are allowing the delegate variable to do that for you, which is the same behavior you get by default with a normal event.

The value of this syntax is that you could opt to store the list of handler methods in a different type of data structure, such as a Hashtable or collection. You could then invoke them asynchronously, or in a specific order based on some other behavior required by the application.

Receiving Events with WithEvents

Now that you have implemented an event within the Person class, you can write client code to declare an object using the WithEvents keyword. For instance, in the project's MainWindow code module, you can write the following code:

Class MainWindow
  Private WithEvents mPerson As Person

By declaring the variable WithEvents, you are indicating that you want to receive any events raised by this object. You can also choose to declare the variable without the WithEvents keyword, although in that case you would not receive events from the object as described here. Instead, you would use the AddHandler method, which is discussed after WithEvents.

You can then create an instance of the object, as the form is created, by adding the following code (code file: MainWindow.vb):

Private Sub Window_Loaded_1 (sender As System.Object, _
    e As RoutedEventArgs)        
  mPerson = New Person()
        
End Sub

At this point, you have declared the object variable using WithEvents and have created an instance of the Person class, so you actually have an object with which to work. You can now proceed to write a method to handle the Walked event from the object by adding the following code to the form. You can name this method anything you like; it is the Handles clause that is important, because it links the event from the object directly to this method, so it is invoked when the event is raised (code file: MainWindow.xaml.vb):

Private Sub OnWalk(ByVal Distance As Integer) Handles mPerson.Walked
  MessageBox.Show("Person walked a total distance of " & Distance)
End Sub

You are using the Handles keyword to indicate which event should be handled by this method. You are also receiving an Integer parameter. If the parameter list of the method doesn't match the list for the event, then you'll get a compiler error indicating the mismatch.

Finally, you need to call the Walk method on the Person object. Modify the Click event handler for the button (code file: MainWindow.xaml.vb):

Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
        
  mPerson.Walk(42)
        
End Sub

When the button is clicked, you simply call the Walk method, passing an Integer value. This causes the code in your class to be run, including the RaiseEvent statement. The result is an event firing back into the window's code, because you declared the mPerson variable using the WithEvents keyword. The OnWalk method will be run to handle the event, as it has the Handles clause linking it to the event.

Figure 3.13 illustrates the flow of control, showing how the code in the button's Click event calls the Walk method, causing it to add to the total distance walked and then raise its event. The RaiseEvent causes the window's OnWalk method to be invoked; and once it is done, control returns to the Walk method in the object. Because you have no code in the Walk method after you call RaiseEvent, the control returns to the Click event back in the window, and then you are done.

Figure 3.13 Flow of control from button click

3.13

Note
Many people assume that events use multiple threads to do their work. This is not the case. Only one thread is involved in the process. Raising an event is like making a method call, as the existing thread is used to run the code in the event handler. Therefore, the application's processing is suspended until the event processing is complete.

Receiving Events with AddHandler

Now that you have seen how to receive and handle events using the WithEvents and Handles keywords, consider an alternative approach. You can use the AddHandler method to dynamically add event handlers through your code, and RemoveHandler to dynamically remove them.


Note
The WithEvents and the Handles clause are typically the preferred method for handling events on an object. However, there are situations where you might need more flexibility.

WithEvents and the Handles clause require that you declare both the object variable and event handler as you build the code, effectively creating a linkage that is compiled right into the code. AddHandler, conversely, creates this linkage at run time, which can provide you with more flexibility. However, before getting too deeply into that, let's see how AddHandler works.

In MainWindow, you can change the way the code interacts with the Person object, first by eliminating the WithEvents keyword:

Private mPerson As Person

And then by also eliminating the Handles clause:

Private Sub OnWalk(ByVal Distance As Integer)
  MsgBox("Person walked a total distance of " & Distance)
End Sub

With these changes, you've eliminated all event handling for the object, and the form will no longer receive the event, even though the Person object raises it.

Now you can change the code to dynamically add an event handler at run time by using the AddHandler method. This method simply links an object's event to a method that should be called to handle that event. Anytime after you have created the object, you can call AddHandler to set up the linkage (code file: MainWindow.xaml.vb):

Private Sub Window_Loaded_1 (sender As System.Object, _
    e As RoutedEventArgs)
        
   AddHandler mPerson.Walked, AddressOf OnWalk
 End Sub

This single line of code does the same thing as the earlier use of WithEvents and the Handles clause, causing the OnWalk method to be invoked when the Walked event is raised from the Person object.

However, this linkage is performed at run time, so you have more control over the process than you would have otherwise. For instance, you could have extra code to determine which event handler to link up. Suppose that you have another possible method to handle the event for cases when a message box is not desirable. Add this code to MainWindow:

Private Sub LogOnWalk(ByVal Distance As Integer)
  System.Diagnostics.Debug.WriteLine("Person walked a total distance of " &
                                     Distance)
End Sub

Rather than pop up a message box, this version of the handler logs the event to the output window in the IDE, or in the real world to a log file or event log as shown in Chapter 6. First add a new Setting to the application using the Project Properties. Name the property “NoPopup,” give it the type Boolean and Application scope. You can accept the default value of false. Now you can enhance the AddHandler code to determine which handler should be used dynamically at run time (code file: MainWindow.xaml.vb):

Private Sub Window_Loaded_1 (sender As System.Object, _
    e As RoutedEventArgs)  
  If My.Settings.NoPopup Then
    AddHandler mPerson.Walked, AddressOf LogOnWalk
  Else
    AddHandler mPerson.Walked, AddressOf OnWalk
  End If
End Sub

If the setting NoPopup is true, then the new version of the event handler is used; otherwise, you continue to use the message-box handler.

The counterpart to AddHandler is RemoveHandler. RemoveHandler is used to detach an event handler from an event. One example of when this is useful is if you ever want to set the mPerson variable to Nothing or to a new Person object. The existing Person object has its events attached to handlers, and before you get rid of the reference to the object, you must release those references:

If My.Settings.NoPopup Then
  RemoveHandler mPerson.Walked, AddressOf LogOnWalk
Else
  RemoveHandler mPerson.Walked, AddressOf OnWalk
End If
mPerson = New Person

If you do not detach the event handlers, the old Person object remains in memory because each event handler still maintains a reference to the object even after mPerson no longer points to the object. While this logic hasn't been implemented in this simple example, in a production environment you would need to ensure that when mPerson was ready to go out of scope you cleaned up any AddHandler references manually.

This illustrates one key reason why the WithEvents keyword and Handles clause are preferable in most cases. AddHandler and RemoveHandler must be used in pairs; failure to do so can cause memory leaks in the application, whereas the WithEvents keyword handles these details for you automatically.

Constructor Methods

In Visual Basic, classes can implement a special method that is always invoked as an object is being created. This method is called the constructor, and it is always named New.

The constructor method is an ideal location for such initialization code, as it is always run before any other methods are ever invoked, and it is run only once for an object. Of course, you can create many objects based on a class, and the constructor method will be run for each object that is created.

You can implement a constructor in your classes as well, using it to initialize objects as needed. This is as easy as implementing a Public method named New. Add the following code to the Person class (code file: Person.vb):

Public Sub New()
  Phone("home") = "555-1234"
  Phone("work") = "555-5678"
End Sub

In this example, you are simply using the constructor method to initialize the home and work phone numbers for any new Person object that is created.

Parameterized Constructors

You can also use constructors to enable parameters to be passed to the object as it is being created. This is done by simply adding parameters to the New method. For example, you can change the Person class as follows (code file: Person.vb):

Public Sub New(ByVal name As String, ByVal birthDate As Date)
  mName = name
  mBirthDate = birthDate
  Phone("home") = "555-1234"
  Phone("work") = "555-5678"
End Sub

With this change, anytime a Person object is created, you will be provided with values for both the name and birth date. However, this changes how you can create a new Person object. Whereas you used to have code such as

Dim myPerson As New Person()

now you will have code such as

Dim myPerson As New Person("Bill", "1/1/1970")

In fact, because the constructor expects these values, they are mandatory—any code that needs to create an instance of the Person class must provide these values. Fortunately, there are alternatives in the form of optional parameters and method overloading (which enables you to create multiple versions of the same method, each accepting a different parameter list). These topics are discussed later in the chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset