Creating Classes in Visual Basic
Creating Classes in Visual Basic
NET
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
Assumptions
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
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,
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 1/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
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.
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.
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 2/9
9/21/2018 Creating Classes in Visual Basic .NET
Figure 1. This form allows you to test each property and method of your Line class
ReadOnly True
Text
ReadOnly True
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:
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 3/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
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
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 4/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
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.
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:
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 5/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
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.
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."
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 6/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
Try It Out
Follow the steps below to try out this new GetWord method you just wrote.
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.
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 7/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
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.
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.
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
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 8/9
9/21/2018 Creating Classes in Visual Basic .NET
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.
© 2018 Microsoft
https://msdn.microsoft.com/en-us/library/ms973814(d=printer).aspx 9/9