Using VS - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Using VS arrow OOP in .NET: The How and Why, Part 3
OOP in .NET: The How and Why, Part 3
By Peter Aitken

Rate This Article: Add This Article To:

In this final article in his series about the basics of OOP in .NET, Peter Aitken explains class constructors and class events.

This is the third and last in a series of three articles on object-oriented programming in .Net.

Class Constructors

ADVERTISEMENT

Most classes include a constructor, a special procedure that is called automatically when the class is instantiated. Constructors are useful when you need to initialize an object when it is created. To create a constructor simply add a procedure named New to the class:

Class SomeClass
    Public Sub New()
    ' Initialization code is placed here.
    End Sub
...
End Class

You can define constructors that take arguments, permitting a program to pass initialization information to an object when it is first created. In fact, a class can have more than one constructor as long as they take different arguments. They will all have the name New; .Net will know which one to call based on the arguments passed by the calling program. Here's an example of a class with a property named Count. The default constructor, with no arguments, initialized this property to 0. Another constructor, taking one type Integer argument, initializes the property to the value that is passed:

Public Class Items

    Public Count As Integer
    Public Sub New()
        Count = 0
    End Sub

    Public Sub New(ByVal x As Integer)
        Count = x
    End Sub

End Class

Then you would instantiate the class Items in one of two ways:

Dim obj1 As New Items
Dim obj1 As New Items(12)

Class Events

A class definition can include one or more events that the class can raise. These are not the same as user events, such as key presses and mouse clicks. Rather, they are internal events that can be triggered in code and detected by the program. Such events are useful in a variety of programming situations, such as a class that performs some time-consuming operation and wants to notify the program of its progress. There are four parts to defining and using a class event.

First, you must define the event in the class with the Event keyword. The syntax is:

Public Event EventName(ArgumentList)

Second, you must raise the event from within the class using the Raise Event statement:

Raise Event EventName(ArgumentList)

Third, when you instantiate the class you must include the WithEvents keyword in the declaration:

Public WithEvents obj As ClassName

Fourth and finally, you must write, outside the class, a procedure that will handle the event. This is a regular Visual Basic Sub procedure with the following two requirements:

  • Its argument list must match the argument list of the event.
  • It must include the Handles keyword and a list of the events it will handle.

For example:

Private Sub SubName(ArgumentList) Handles EventList
...
End Sub

The EventList contains one or more events that the procedure will handle. Each event is identified by the object name (not the class name) and the event name in the Objectname.EventName format.

Let's look at an example. I have written a class that mimics performing a lengthy calculation or download by executing a loop many thousands of times. It includes an event called Progress that reports the percent of the task that is complete to the calling program. Code for the class is shown here:

Public Class ClassWithEvent

    Public Event Progress(ByVal PercentDone As Integer)

    Public Sub DoSomething()
       Dim x As Integer, y As Integer

        For x = 0 To 100 Step 10
            RaiseEvent Progress(x)
            For y = 0 To 50000
                Application.DoEvents()
           Next
        Next
    End Sub

End Class

Note the call to the Application.DoEvents() method in the loop. This call permits the application to handle other events while the code — in this case the inner loop — is executing. Without this call, new events, such as those for refreshing the TextBox display, would wait in the event queue, and the TextBox display would not update from 0 to 10, 20, etc. as it is supposed to but would jump from 0 to 100 when the loop is finished.

To try out this class, create a new Visual Basic Windows application in .Net, and place one Command Button and one TextBox on the form. Then:

  • Add the class source code from above to the project.
  • Add a declaration with the WithEvents keyword:
  • Dim WithEvents obj As ClassWithEvent
  • Create an event handler for the event that displays the percent done value passed by the event in the TextBox:
  • Protected Sub obj_progress(ByVal PercentDone As Integer) 
        Handles obj.Progress
        TextBox1.Text = PercentDone
    End Sub
  • Create a click handler for the button that sets things in motion:
  • Private Sub Button1_Click(ByVal sender As System.Object,
     ByVal e As System.EventArgs) Handles Button1.Click
        obj = New ClassWithEvent
        obj.DoSomething()
    End Sub

    When you run the project, click the button and you'll see the TextBox update as the processing progresses.

    Summary

    You really will not be getting the full benefit of Visual Studio.Net until you start using its object-oriented programming capabilities. OOP may seem difficult to learn at first, but it is well worth the effort. These articles have provided a quick introduction, and you should continue to explore to topic in the MSDN documentation, books, magazine articles, and online newsgroups. In my experience, every hour you spend learning OOP is repaid ten or a hundred times over down the road in reduced development, debugging, and maintenance time. I only wish other investments paid off so well!




    Discuss OOP in .NET: The How and Why, Part 3
     
    >>> Be the FIRST to comment on this article!
     

     
     
    >>> More Using VS Articles          >>> More By Peter Aitken
     



    Top Technology Pros One-to-one

    All Videos >

    Julia explores the Robotics Studio!

    Read now >

    Messages to Bill Gates!

    Read now >

    View Now
    DevSource RSS FEEDS
    XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.