Creating Classes in Visual Basic .NET

 

Paul D. Sheriff
PDSA, Inc.

November 2001

Summary: This article shows how to create a class in Microsoft Visual Basic .NET, describing the differences between Visual Basic 6.0 and Visual Basic .NET with regard to classes, and tells how to add properties and methods to a class. (11 printed pages)

Objectives

  • Learn to create a class in Microsoft® Visual Basic® .NET
  • Learn the differences between Visual Basic 6.0 and Visual Basic .NET with regard to classes
  • Learn to add properties to a class
  • Learn to add methods to a class

Assumptions

  • You have created classes in Visual Basic 6.0
  • You understand the fundamentals of OOP
  • You know how to build a basic form in Microsoft Visual Studio® .NET

Contents

Object-Oriented Programming Overview
   Good Uses for Classes
   Create a Class
   Creating Properties
   Read-Only Properties
   Create a Write-Only Property
   Create a Method
   Passing Data to a Constructor
   Use Classes for All Your Tasks
Summary
   About the Author

Object-Oriented Programming Overview

Object-Oriented Programming (OOP) is a method of software design and construction. It is the next logical progression, after structured programming, to improve your code reusability and maintainability. Put another way, OOP is a method of designing individual software components (classes) with associated behaviors (methods) and data limitations (properties), and that helps you piece these components together to create a complete application.

The best thing about OOP is that it allows you to group data into discrete variables contained within a class in your program. This data is separate and distinct from any other class in your application. No class can interfere with the data in any other class without going through a specific interface on that class.

Each object defines its functionality as a set of properties and methods that it will respond to. Other code can call these methods on the object and have them perform some behavior and use the properties to retrieve or change some information. In this way, code cannot affect the information or processes of other objects directly. As you build a class, you will see how to build this functionality using properties and methods.

Table 1 is a review of OOP terms that you should already be familiar with prior to reading this document.

Table 1: OOP Terms

Class A container for data and code. The data within the class can be accessed with properties. The code is referred to as methods.
Object An instance of a class in memory. An instance is created using a Dim statement and the New keyword.
Constructor A procedure that is automatically invoked when an object is first instantiated. In Visual Basic 6.0, the constructor was called Class_Initialize. In Visual Basic .NET the constructor is called New.
Destructor A procedure that is automatically invoked when an object is destroyed. In Visual Basic 6.0, the destructor was called Class_Terminate. In Visual Basic .NET, the destructor is called Finalize.
Properties A routine exposed by an object to expose data, and to allow code outside the object to affect the objects data.
Method An action that can be performed by an object. In Visual Basic .NET, methods are defined as Subs and Functions.

Good Uses for Classes

Classes are the heart and soul of an object-oriented language. You will find yourself using classes whenever you write even the simplest of programs in Visual Basic .NET. The Microsoft .NET Framework makes extensive use of classes, and so should you. Below are some common uses of classes:

  • Wrapping up the representation and set of operations you perform on a database table, for example adding, editing, deleting, and retrieving data.
  • Wrapping up the set of operations and data for dealing with text files such as reading, writing, and indexing the lines of text within the file.
  • Wrapping up all global variables in a program into properties within a class. This can help with keeping track of the amount of "free-floating" globals that somehow seem to work their way into many programs.

Create a Class

Let's create a class representing a line of text. To do this, you create a property to return the line of text and a read-only property that returns the length of the text. You will also create a method that returns the first word in the line. As you perform all of these steps, you will learn the correct way to create a class. You will build a form like the one shown in Figure 1 to test the Line class as you build it.

Figure 1. This form allows you to test each property and method of your Line class

To create the form

  1. Open Visual Studio .NET.

  2. Select Visual Basic Project from the tree-view on the left-hand side of the screen.

  3. Select Windows Application as the project template.

  4. Set the name of the application to ClassCreation.

  5. In the Solution Explorer window, select the Form1.vb form and rename it to frmLineTest.vb. To rename a form in the Solution Explorer window, right-click the form and choose Rename on the shortcut menu.

  6. Create the form shown in Figure 1 by adding the appropriate controls and setting the properties of those controls as outlined in Table 2.

    Table 2: Controls used to build the form to test the Line class

    Control Type Property Value
    Label Name Label1
      Text Line of Text
    TextBox Name txtLine
      Text The rain in Spain stays mainly in the plain
    CommandButton Name btnDisplay
      Text Display Length
    TextBox Name txtLength
      ReadOnly True
    CommandButton Name btnGetWord
      Text Get Word
    TextBox Name txtWord
      Text  
      ReadOnly True

To create the Line class

  1. Open the Add New Item dialog box by clicking Project and then clicking Add Class.

  2. Set the Name property to Line and click OK.

  3. You will now see a new file appear in your project and a code window within the Visual Studio .NET environment. In the Code window, there will be some code that looks like this:

    Public Class Line
    
    End Class
    

    All of the properties and methods that you create for this class must be entered between these lines of code.

Creating Properties

To create a property within a class, you can either create a field (ie. a Public variable), or you can create a Private variable and expose the Private variable using a Property statement. There are several reasons why you want to only expose properties through a Property statement.

  • You can create a read-only or write-only property, as opposed to a Public variable, which will always be read-write.
  • You can add error handling within a Property statement to check for invalid values being set. You can't check for invalid values when setting a Public variable because there is no code that runs in response to setting a Public variable.
  • You can expose calculated values as properties even if they are not stored as actual data within the class. An example of this is a Length property. You probably don't want to store the length of a line of text, as it could change.

You will now create two properties named Line and Length for the Line class. You will first create a private variable to hold the line of data that you store within the class. Next, you will create the Property statements for these two new properties. Modify the class in your project so it looks like the code shown below.

Public Class Line

    Private mstrLine As String

    Property Line() As String
        Get
           Return mstrLine
        End Get
        Set(ByVal Value As String)
            mstrLine = Value
        End Set
    End Property
     
    ReadOnly Property Length() As Integer
       Get
           Return mstrLine.Length
       End Get
    End Property
End Class

The syntax for creating a property is fairly simple, but quite different from what you did in Visual Basic 6.0. You first use the keyword Property, followed by a name of the property, and then the type of data this property will return or set. To return the data contained in the private variable mstrLine, you use the Get…End Get block. This block is like the old Property Get function in Visual Basic 6.0. This block of code executes any code between the Get…End Get block and returns a string value. In Visual Basic .NET, you can use the Return statement to return data.

The Set…End Set block is like the old Property Let procedure you used in Visual Basic 6.0. This block accepts a parameter named Value. Value is the default name that is automatically created for you by Visual Studio. You can change it if you want. You can take the value passed to this Set block and place it into your private variable. This is the point where you can place any error handling code you wish. For example, you might check to make sure that the data passed to the Value parameter is not filled in with a word like Test. If a junk word is passed in, you might choose to raise an error that this is not a valid value for this property.

Read-Only Properties

In the code above, you also created a read only property by using the ReadOnly keyword in front of the Property statement. When you use this keyword, Visual Studio .NET adds a Get…End Get block to the Property statement. In fact, if you try to add a Set…End Set block, you will receive a compiler error. If you wanted to create a read-only property in Visual Basic 6.0, you did not create the Property Let procedure, but no error was generated if you left it off. You just were unable to set the property at run time.

Try It Out

In the project you have created, you have one class and one form. You will now write code in the form that creates a new Line object, places a line of text into the Line property of your object, and then places the length of the line into the Text property of the txtLength text box on your form.

  1. In the Solution Explorer window, double-click the frmLineTest form to bring up the form in design mode.

  2. Double-click the Display Length button. Visual Basic .NET creates a btnDisplay_Click event procedure for you in the code behind this form. All you need to do is fill in the lines of code shown below, in the body of the procedure.

    Private Sub btnDisplay_Click( _
      ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles btnDisplay.Click
    
        Dim oLine As Line 
    
        oLine = New Line()
    
        oLine.Line = txtLine.Text
        txtLength.Text = oLine.Length.ToString()
    End Sub
    

Within this event procedure, you create a variable named oLine by using the Dim statement. This variable is defined as a reference to a Line class. You actually create the new object reference by using the New keyword, as shown in the next line after the Dim statement. The New keyword must be followed by the name of the class you wish to instantiate. Another difference between Visual Basic .NET and Visual Basic 6.0 is that you no longer use the Set keyword when creating a new object.

In Visual Basic .NET, you are allowed to combine these two lines into one, as shown in the code below.

Dim oLine As Line = New Line()
Or
Dim oLine as New Line()

Visual Basic .NET (and all .NET languages) allow you to declare and initialize any variable on the same line. In Visual Basic 6.0, you were unable to do this, as the Dim statement was not an executable line of code. In Visual Basic .NET, Dim is an executable line of code so this syntax is perfectly legal.

Now let's examine the next two lines of this event procedure:

oLine.Line = txtLine.Text
txtLength.Text = CStr(oLine.Length)

The first line sets the Line property in your object to be equal to the value contained in the Text property of the txtLine text box on the form. This passes the data in the Text property to the Value variable in the Set…End Set block in the Line object.

Now you are ready to report back the length of the string contained in the txtLine text box. Remember, you set the value of this text box equal to the string "The rain in Spain stays mainly in the plain." This is the value that is contained in the mstrLine variable within your object. You can invoke the Length property on your Line object and it will return the length of this particular string. Because the Length property is an Integer value, you need to convert that value to a string before you can place it into the Text property of the txtLength text box. You accomplish this by applying the ToString method to the Length property.

Create a Write-Only Property

A write-only property is one that defines a Set…End Set block and no Get…End Get block. You are allowed to place data into this property only at run time, but are unable to retrieve data from this property.

If you wanted to extend this Line class to be able to read the line of text in from a file on disk, you might pass the file name to this class. You could accomplish this by using a write-only property. Here is an example of what a write-only property might look like.

WriteOnly Property FileName() As String
    Set(ByVal Value As String)
        mstrFileName = Value
    End Set
End Property

This syntax is again different from Visual Basic 6.0 in that you use the WriteOnly keyword as a prefix to the Property statement. Visual Studio .NET creates the Set…End Set block for you automatically. If you try to add a Get…End Get block, the compiler will give you an error.

Create a Method

A method in a class can be a procedure that performs some sort of operation on the data within the class. Or a method could be a function that performs some operation on the data, and returns that data back from the class. To be able to call a method from an instance of this class, the method must be declared Public. If a method is declared Private, only other methods within the class can call that method. Creating a method in Visual Basic .NET is exactly the same as in Visual Basic 6.0.

Let's create a method in the Line class that breaks up the line of text passed into the class into each separate word. This method is a function that returns the first word contained in the line of text you pass in. If you used the string that was given to you when creating the form, the line of text will be "The rain in Spain stays mainly in the plain." In this case, the first word returned will be "The."

  1. Open the Line.vb class in design mode.

  2. Just below your Property statements, create the following method:

    Public Function GetWord() As String
        Dim astrWords() As String
    
        astrWords = Split(mstrLine, " ")
    
        Return astrWords(0)
    End Function
    

The GetWord method converts the string to an array of individual words using the Split function. The Split function has been around since Visual Basic 6.0 and is passed a string and a delimiter to find. Split starts with the first character in the string and continues moving through the string until it finds the delimiter. Once found, it takes all of the string up to that point and creates a new array element. It then continues processing the string in this manner until the complete string has been put into array elements.

After converting the string to an array, you may return any word in the sentence you pass into the Line class. This example only returns the first word by accessing the first element of the array. In Visual Basic .NET, all arrays are zero-based just like the default in Visual Basic 6.0. The difference here is that you cannot make anything other than a zero-based array in Visual Basic .NET and you could in Visual Basic 6.0.

Note Another way you could have written the code to separate the words in the mstrLine variable into an array is to use the Split method on the String object as shown below.

astrWords = mstrLine.Split(" ".ToCharArray())

Try It Out

Follow the steps below to try out this new GetWord method you just wrote.

  1. Open the frmLineTest form in design mode.

  2. Double-click the Get Word button. This will open the code window with the btnGetWord_Click event procedure created for you.

  3. Add the following code to this event procedure, as shown in the example below.

    Private Sub btnGetWord_Click(ByVal sender As Object,_
     ByVal e As System.EventArgs)
    
        Dim oLine As New Line()
    
        oLine.Line = txtLine.Text
        txtWord.Text = oLine.GetWord()
    
    End Sub
    

This event procedure first creates a new instance of the Line class into the object variable oLine. You next set the Line property on the line class by getting the value from the Text property of the txtLine text box. Finally, you call your new GetWord method and it returns a string value. This value is assigned into the Text property of the txtWord text box you created on the frmLineTest form earlier in this paper.

Passing Data to a Constructor

In Visual Basic 6.0, you were unable to pass data when you created a new instance of a class. This meant you had to create the object, remember to call an initialization method, and pass data to that method. If you forgot to initialize the object, your object failed. Although you might remember to call this initialization method, if other programmers used your class, they may not know to call it.

This problem has been solved in Visual Basic .NET as the constructor method can now be passed data. The constructor method is called New in Visual Basic .NET. By default, Visual Basic .NET creates this New method for you without you having to do anything. You won't see this code within your code module, but it is there implicitly. If you wish to pass some data to this New method, you need to explicitly create it.

You can place the New constructor anywhere within your class, but you might want to choose a standard location, such as always near the top of your class definition. In this next exercise, you create a New constructor that accepts a String value. By doing this, you will be able to declare, initialize an object variable, and set the data for the Line object, all in one step.

  1. Open the Line.vb class in your project.

  2. Add the Sub New, as shown below, to your Line class:

    Public Class Line
        Private mstrLine As String
    
        Public Sub New(ByVal Value As String)
            mstrLine = Value
        End Sub
    

The New constructor is a procedure that you write to accept one or more parameters. In the code you just wrote, you created a parameter called Value. You then took the value and assigned it to the private variable mstrLine. Now you need to change the procedures in your form, so you pass the value from txtLine text box to the constructor.

  1. Open your frmLineTest.vb form.

  2. You will need to change both the btnDisplay_Click event procedure and the btnGetWord_Click event procedures to declare the oLine variable as shown below.

    Dim oLine As New Line(txtLine.Text)
    

The New keyword tells Visual Basic .NET to create a new instance of Line and pass the data that is contained within the Text property of the txtLine text box to the New constructor.

You need to change both event procedures before you can run the project. By changing the New procedure to accept a parameter, any declaration of the Line class must now pass some data when declaring the object.

Try It Out

After making the changes to the event procedures, you are ready to try running the program again to make sure you did it correctly.

  1. Press F5 to run this application.
  2. If you receive any errors, fix them and try it again.

Use Classes for All Your Tasks

It's a good idea to create classes for all of your programming tasks. Visual Basic .NET will still let you create stand-alone functions and procedures within a module. But there are quite a few advantages to using classes (and objects) over traditional structured programming techniques:

  • Calculations or operations are encapsulated (wrapped-up) into an easy-to-use interface. This helps newer programmers tackle the problem at hand without having to know how everything works. It also helps the old pros speed up their development time considerably.
  • It is easy to change the internal workings of a class to make it perform better. Any program that uses this class receives the benefit of the improved performance.
  • It is possible to have multiple instances of a class active in memory at one time. This eliminates the need to create multiple Public variables when you wish to compare multiple values from one source against values from another.
  • It is possible to inherit from a class and extend the functionality without changing the original class. Inheritance is covered in a separate document, named "Inherit from a Base Class."

What's Different in Visual Basic .NET From Visual Basic 6.0

There are a lot of differences in how classes are created in Visual Basic .NET from Visual Basic 6.0. Below is a list of the major ones.

  • You now use Public Class…End Class to define a class. In Visual Basic 6.0, each class had to be in its own separate file.
  • You can have multiple classes per file.
  • Declarations of properties are completely different from Visual Basic 6.0.
  • You no longer use the Set keyword to instantiate a new instance of a class, or to set an object reference.
  • You can now pass in parameters to the constructor of a class.

Summary

You have now created a class that has one read/write property, a read-only property, and a method. You also passed data into the constructor of this class. As mentioned in the beginning of this paper, OOP is about the ability to piece together software components that help you create your applications more easily. By creating a Line class, you did not have to remember the details of how to calculate the length of a line of text, or use the Split function to return the first word of a line of text. Instead, you used a Line class, passed it the line, and used properties and methods to do these operations for you. This is a much more elegant approach to programming.

About the Author

Paul D. Sheriff is the owner of PDSA, Inc. (www.pdsa.com), a custom software development and consulting company in Southern California. Paul is the MSDN Regional Director for Southern California, is the author of a book on Visual Basic 6 called Paul Sheriff Teaches Visual Basic, and has produced over 72 videos on Visual Basic, SQL Server, .NET and Web Development for Keystone Learning Systems. Paul has co-authored a book entitled ASP.NET Jumpstart. Visit the PDSA, Inc. Web site for more information.

About Informant Communications Group

Informant Communications Group, Inc. (www.informant.com) is a diversified media company focused on the information technology sector. Specializing in software development publications, conferences, catalog publishing and Web sites, ICG was founded in 1990. With offices in the United States and the United Kingdom, ICG has served as a respected media and marketing content integrator, satisfying the burgeoning appetite of IT professionals for quality technical information.

Copyright © 2001 Informant Communications Group and Microsoft Corporation

Technical Editing: PDSA, Inc. and KNG Consulting