VB .NET Chapter 12 Classes and Objects

VB.NET Classes and Objects

VB.NET is an Object Oriented programming language. The Objects referred to are created from something called a Class. You've already used Classes throughout this course. But we'll now have a closer look at them.

Object Oriented programming

The modern trend in programming languages is for code to be separated into chunks. When it's being used, each chunk of code (a chunk of code that opens text files, for example) is known as an Object. The code for the Object can then be reused whenever it is needed. Languages like C++ and Java are Object Oriented languages. Until Microsoft came out with VB.NET, the Visual Basic programming language was not OOP (object oriented programming). This time it is.
Object Oriented programming has a steeper learning curve, and things like Encapsulation, Inheritance and Polymorphism have to be digested. We're not going quite that far in this beginner's course. But you should have a good, basic understanding of just what Object are by the end of this section, and how to create your own Objects.

Classes and Objects

In VB.NET, a class is that chunk of code mentioned earlier. You've been using Classes all the time during this course. The Form you've started out with is a Class. If you look right at the top of the code window for a Form, you'll see:
Public Class Form1
The word "Public" means that other code can see it. Form1 is the name of the Class
If you look at the bottom of the coding window, you'll see End Class, signifying the end of the code for the Class.
When you place a Button or a textbox on the Form, you're really adding it to the Form Class.
When you start the Form, VB does something called instantiation. This basically means that your Form is being turned into an Object, and all the things needed for the creation of the Form are being set up for you (Your controls are being added, variables are being set up an initialised, etc).
And that's the basic difference between a Class and an Object: A Class is the code itself; the code becomes an Object when you start using it.

The NET Framework

The NET Framework is something that Microsoft have invested a lot of time, effort and money into creating. It's big. Very big. The way that programming will be done on a Microsoft machine from now on is with NET. And not just on a Microsoft machine. There's something called ADO.NET which is used for creating web site, and for manipulating databases. You can create applications for mobile phones and PDA's with NET. There is even a project in the making that will allow you to write a programme on a Windows machine that will then work on a computer NOT running Windows. All this is made possible with the NET Framework. But what is it?
The NET Framework is a whole lot of Classes (called Namespaces) and the technology to get those Classes to work. The main component is called the Common Language Runtime. A Runtime is the thing that gets your code to actually run on a computer. Previously, these Runtime Languages were machine or programming language specific. The Runtime that gets a Java programme to work, for example, is different to the one that gets a C programme to work. With NET, more than 15 different programming languages can use the Common Language Runtime. One of these languages is, of course Visual Basic NET. Another is C# (pronounce C Sharp). They can all use the Common Language Runtime because of something called the Intermediate Language. (This is a sort of translator for the various languages, and is too advanced to go into for us.)


A Namespace is a group of Classes which are grouped together. The System.IO Namespace you met earlier groups together Classes that you use to read and write to a file. System.Windows.Forms is another Namespace you've met. In fact, you couldn't create your forms without this Namespace. But again, it is just a group of Classes huddling under the same umbrella.
System itself is a Namespace. It's a top-level Namespace. Think of it as the leader of a hierarchy. IO and Windows would be part of this hierarchy, just underneath the leader. Each subsequent group of Classes is subordinate to the one the came before it. For example Forms is a group of Classes available to Windows, just as Windows is a group of Classes available to System. A single form is a Class available to Forms:
The dot notation is used to separate each group of Classes. A Button is also part of the Forms Class:
As too is a Textbox:
The leader of the hierarchy is still System, though. Think of it as an army. You'd have a Private who is subordinate to a Sergeant. The Sergeant would be subordinate to a Captain. And the Captain would be subordinate to a General. If the General wanted something done, he might ask the Captain to do it for him. The Captain would get the Sergeant to do it, and the Sergeant would then pick on a poor Private. So Button would be the Private, Forms would be the Sergeant, Windows would be the Captain, and System the General.
In other words, there is a chain of command in NET programming. And if you don't follow the chain of command, you're in trouble!
But you see this chain of command every time you type a full stop and a pop up box appears. When you're selecting an item from the list, you're selecting the next in the chain of command.
This code at the top of the form window:
Inherits System.Windows.Forms.Form
means you don't have to keep typing the full chain of command every time you want to access a button on the form. This chain of command is inherited whenever you create a new VB.NET Form. There are plenty of times when a chain of command is not inherited though, and in that case you do have to type it all out. You did this when you referenced a StreamReader with:
The IO Namespace is not inherited when you created a new Form, so you have to tell VB where it is in the hierarchy.
But that's not quite the end of the story. The reason you using all of these long Namespaces is to get at a Property or Method - the chaps that do all the actual work! When you type Button1.Text = "Click Me", Text is a Property of Button1. Button belongs to Form, which belongs to Forms, which belongs to Windows … etc.
So whenever you access a Property or Method of a control, just remember that rather long chain of command.

Create your own Classes in VB .NET

The big benefit of an Object Oriented Programming language is that you can create your own Objects. (It's an Object when you're using the code, remember, and a Class when you're not.)
We'll see how to do that now, as we create a very simple Class, and then turn that into an Object.
The Class we'll create is a very simple one, and is intended to show you the basic technique of setting up a Class, then creating an object from it. The Class we'll create will convert the letters in a postcode to uppercase. We'll get the postcode from a textbox on a form. Off we go then.
  • Start a new VB .NET project
  • Add a Textbox to your form, and leave it on the default Name, TextBox1
  • Change the Text Property to ts1 4jh (make sure the letters are lowercase and not upper, because our object will convert it.)
  • Add a Button to your form
Once you have a new form with a Textbox and a Button on it, you need to add a Class. This is quite easy. It's just like adding a Module. In fact, they look exactly the same!
  • So from the VB menu bar, click on Project
  • From the drop down menu, click Add Class
  • You'll get this dialogue box popping up in version 2008:
The Add New Item dialogue box
In version 2010, the dialogue box looks like this (version 2012/13 will be a less colourful version of the one below):
Add New Item - Class
The Class Template on the right will already be selected. The thing you need to change is theName at the bottom. The default Name is Class1.vb. This is not terribly descriptive, and you'll have great problems working out what this class does, a few months down the line.
Change the Name from Class1.vb to ConvertPostcode.vb. Then click the Open button.
When the code window for the class opens up, it will look like this:
The Class code window
As you can see, there's not a great deal to look at! All we have is the Public Class … End Classcode stub. The name of our Class is also there. But the code is in a separate window, and has a tab all to itself. It's this tab full of code that you reuse and turn into an object.
What we have to do now is add the code that does the work - converts our postcode. But we can't just write this:
Dim ConvertPostcode As String
ConvertPostcode = StrConv( TextBox1.Text, VbStrConv.UpperCase )
TextBox1.Text = ConvertPostcode

That would be all right for the button on our Form. But it's not all right for our Class. When you're designing a Class, your code has to go inside of things like Functions and Subs. You'll also see how to create your own properties for your objects.
When you set up a Function or Sub, you're actually creating Methods for your objects (A Method is code that actually does something, that performs an action. Converts a postcode in our case.) 

Create Methods in your VB .NET Classes

A method created in a Class is nothing more that a Function or a Sub. You've seen how to do this in an earlier section. The process is the same. So add the following code to the Class you created for the previous lesson:
Public Function DoConvert(ByVal postcode As String) As String
Dim ConvertPostcode As String
ConvertPostcode = StrConv(postcode, VbStrConv.UpperCase)
DoConvert = ConvertPostcode

End Function
When you've finished typing it all, you Class should look like this in the code window:
The Function inside of your class
All we've done is to set up a Public (not private) function. We've given it the name "DoConvert". We've set it up to accept one parameter, a String variable called postcode. This is the value that will be handed to our function. The function itself has been set up as a String. This means that DoConvert will be just like a string variable that we can assign a value to.
The code itself you've met before. It uses the in-built StrConv function to do the actual job of converting the string to uppercase letters.
Now that we've set up a Method, let's see how to create an object from our Class, and put the Method to use.

Creating an Object from a Class

Our function is not much use until we can get it up and running. (Here, "Get it up and running" means create an object from our class.) To do that, double click the button on your Form, and add the following code to it:
Dim NewCode As String
Dim objConvertPostcode As ConvertPostcode
objConvertPostcode = New ConvertPostcode
NewCode = objConvertPostcode.DoConvert(TextBox1.Text)
TextBox1.Text = NewCode
The first line just sets up a new String variable called NewCode. Whatever is returned from our function will be stored inside of this variable.
The next line is where the action starts:
Dim objConvertPostcode As ConvertPostcode
The variable name objConvertPostcode is just something we made up ourselves. The "obj" prefix means Object, and this is for our benefit, to remind us that the type of data inside it holds an Object, rather than a plain old Integer or String.
After you type the word "As", then hit your spacebar, you'll see s popup box appear. If you type the letters "conv", you'll see the list automatically move down. The Class your created should be on that list, as in the next image:
The name of our Class is on the list
You can double click the name of your Class to add it to your code (or press the Tab key on your keyboard).
But what you're doing in this step is setting up a pointer to your Class. You're telling VB where the Class can be found, and then storing this inside of the variable called objConvertPostcode. If VB doesn't know where your Class is then it can't create an Object from it.
The next line of code is the one that creates a new object from your Class:
objConvertPostcode = New ConvertPostcode
You type the Name of your variable first, then an equals sign. To the right of the equals sign comes the word "New". This is what tells VB to create a New Object. And the class its creating the New Object from is the one called ConvertPostcode.
You can actually type all of that on the same line:
Dim objConvertPostcode As ConvertPostcode = New ConvertPostcode
This does two jobs: sets a pointer to where the Class is, and creates a new Object from the Class.
But there's reasons why you don't want to do it this way. One is that Objects take up space in memory. And you only really need to create them when they are needed. For example, what if the textbox was blank? You'd want to check for this and invite the user to try again. If you've written everything on one line, then you've already created the Object before the Textbox has been checked. Instead, you could do something like this:
If TextBox1.Text = "" Then
MsgBox "Please try again"
Exit Sub

objConvertPostcode = New ConvertPostcode
End If
Here's, the textbox is being checked first. If the user has left it blank then we bail out. If not, THEN we create an Object from our Class.
The next line in our code was this:
NewCode = objConvertPostcode.DoConvert(TextBox1.Text )
First, we type the name of the variable we want to store the result of our Method into. In our case, the one called NewCode. After the equals sign, we type the name of our Object variable:
As soon as you type a full stop after your Object variable, you should see a popup box with the name of your new method on the list:
Our Method is on the list!
The image above shows you that the name of our Method "Do Convert" has been recognised by VB. (You can tell it's a Method because of the purple block next to it.) But notice the tool tip - it's the first line from our Function!
In between the round brackets, VB is telling us what type of data needs to be passed over to the Method - a String of text. The second "As String" tells you that the Method returns a value that needs to be stored somewhere.
So if you've set up a Method that returns a value (a Function) then you need to store it in a variable.
To get at the Method inside of your class, first type the name of your Object variable. The type a full stop. Look for the name of your Method in the pop up list that appears.
The final line of the code just assigns the value returned from the Method back to the textbox:
TextBox1.Text = NewCode
Run your code and test it out. Click your Button and you should see the postcode change from "ts1 4jh" to "TS1 4JH".

Creating Methods that don't return a value

In the last part, you created a Method that returned a value. But you Methods do not have to return a value. In which case, you create a Sub and not a Function, like we did the last time. Add the following code to your Class:
Public Sub DoMessageBox()
MsgBox("Conversion Complete")
End Sub
This is a Public Sub that doesn't do anything terribly useful. But it will illustrate how to write code to set up a Method that doesn't return a value. Here's what your coding window should look like:
A Function and a Sub have been added to the Class
To run your new method, return to your Button code. You should have this, remember:
The code for your Button
On a new line after Textbox1.Text = NewCode, type the following:
After you type the name of your Object variable, then a full stop, you get the message box popping up. This time, your new Method is on the list:
Our new Method is on the list!
The tip next to the pop up box is telling you that the Method is a Sub, and that it therefore doesn't return a value. The Sub also has no parameters inside of the round brackets, so you don't have to hand anything to it.
You can double click the new Method to add it to your code. When you press the return key on your keyboard, VB adds a pair of round brackets to the end of the line.
So calling a Method that doesn't return a value is just like calling a Sub. The difference is that you need the name of your Object variable first. If we had set up the Sub inside of the Form1 code, we would have just done this to call it:
But because the Sub was inside of the Class, you first type the name of your Object variable:
Run your code again. Click your button. You should see two things happen: one, the text in the textbox will change; and two, you should see message box popping up confirming the change.

Now that you know how to create Methods for your Classes,

Creating Properties for your Classes

In the previous sections, you have learned how to create a Class in VB .NET. You also learned how to create your own Methods. In this part, you'll learn how to create your own properties.

Creating your own Properties in VB .NET Classes

You can add your own Properties to your Class. A Property, remember, is something that changes or sets a value. Examples are, setting the Text in a textbox, changing the background colour of a Form, and setting a Button to be Enabled.
You can Get values from a Property or Set them. So for a Textbox, you can Set the text to appear in the textbox, or you can Get what text is inside of the textbox. You use these same words, Get and Set, when you're creating your own Properties. An example might clear things up. Before you do the following, download the image you will need for this tutorial:
Once you have the images on your hard drive, do the following:
  • Add a Picture Box control to your Form
  • Set the SizeMode Property of the Picture box to StretchImage
  • Click on the Image Property, and add the planet.jpg image that you downloaded above
  • Add two textboxes to the form. Change the Name of the first one to txtHeight, and the second one to txtWidth. Enter 300 as a the text for both textboxes
  • Add two labels to the form. Set the Text of the first one to Height, and the second one toWidth. Move them next to the textboxes
  • Add a new button to your form. Set the Text property to “Change Height and Width”
What we’ll do is to give our object the capability of setting a Height and Width property. When the object has done its work, the height and width of the picture box will change to the values from the textboxes. Off we go then.
VB needs to know that you want to set up a Property for your Class. The way you do this is type "Public Property … End Property".
Access the code for your Class. Type a few lines of space between the End Sub of your DoMessageBox Method, and the line that reads "End Class". On a new line, type the following:
Public Property ChangeHeight() As Integer
ChangeHeight is the name of our property, and it's something we made up ourselves. After a pair of round brackets, you add the type of value that will be returned (Just like a function). Here, we want to return an Integer value.
When you press the return key after typing that line, VB finishes off the rest of the code stub for you:
Public Property ChangeHeight() As Integer
End Get
Set(ByVal Value As Integer)
End Set
End Property
Before the code is explained, add a new variable right at the top of your code, just below "Public Class changeHeightWidth". Add this:
Private intHeight As Integer
The Private word means that only code inside of the Class can see this variable. You can't access this code directly from a button on a Form, for example.
The reason the variable is right at the top is so that other chunks of code can see and use it.

But your coding window should now look something like this next image:
The code for your Class
With the Get and Set parts, the Property stub is this:
Public Property PropertyName() As VaraibleType
End Property
The reason the Get and Set are there is so that you can Set a value for your property, and get a value back out.
To Set a value, the code inside of Property is this:
Set( ByVal Value As Integer )
End Set
The Set word is followed by a pair of round brackets. Inside of the round brackets is ByVal Value As Integer. The is just like a Sub, when you hand over a value to it. The name of the variable,Value, is a default name. You can change this to anything you like. The type of variable, As Integer, is also a default. You don't have to pass numbers to you property. If you want your Property to handle text you might have something like this:
Set( ByVal MyText As String )
But you couldn't do this:
Set( ByVal Value As Integer, ByVal MyString As String )
In other words, you can't pass two values to your property. You can only pass one value.
But we want to pass a number to our property. For us, this value will come from the textbox on the form. Whatever number is inside of the textbox will get handed over to our Property.
Set( ByVal Value As Integer )
But we need to use this value being handed over. We can assign it to that variable we set up at the top of the Class. So add this to your code (The new line is in bold):
Set(ByVal Value As Integer)
intHeight = Value
End Set
Whenever our Property is called into action, we're setting a Value, and then handing that value to a variable called intHeight. This is known as Writing to a Property.
To read from a Property, you use Get. This will Get a value back out of your Property. The code stub is this:
End Get
You don't need any round brackets for the Get part. You're just fetching something to be read.
Add the line in bold text to your Get statement.
ChangeHeight = intHeight
End Get
All you're doing here is returning a value, just like you do with a function. You're handing a value to whatever name you called your property. We called ours ChangeHeight. It's an Integer. So we can pass whatever value was stored inside of intHeight over to the variable called ChangeHeight:
ChangeHeight = intHeight
You can also use the Return keyword. Like this:
Return intHeight
End Get
Let's see how to use our new Property. (It's not a terribly useful property, by the way. A Picture box already has a Height and Width property that you can use. So ours is a bit redundant. But we're keeping it simple so that you can understand how to create your own properties. And it's not a good idea to put this Property into the code for your ConvertPostcode Class. After all, what has the height and width of a picture box got to do with postcodes? But we've added it here just for convenience sake.)

How to use your new Property

The property you have just created is not much good where it is. You need to be able to call it into action. The way you do that is to create a new object from the Class, and then read and write to your property.
So double click the new button you added to your form. Add the following code to it:
Dim objAlterPicBoxAs ConvertPostcode
Dim NewHeight As Integer

objAlterPicBox = New ConvertPostcode
Two of the line you've already met: the one that creates a pointer to a variable (the first line), and the one that creates a new Object from your Class (the third line). The second line just sets up a variable called NewHeight.
To pass a value to your new Property (the Set part), add this line:
objAlterPicBox.ChangeHeight = Val( txtHeight.Text )
As soon as you type the name of your object variable, then a full stop, you'll see the pop up box appear:
Your new Property is on the list
You should see your new Property on the list - ChangeHeight. (You can tell it's a Property because the symbol next to it is a hand holding a card.) If you double click the Property, the code is added for you.
After typing an equals sign, you then assign a value to your new property. Here, we're just passing the property whatever value is inside of the textbox called txtHeight.
But we need to Get a value back out, so that we can do something with it. The way you Get at values is to put your code that accesses the property on the right hand side of an equals sign. On the left, You need the name of a variable.
So add the following to your code:
NewHeight = objAlterPicBox.ChangeHeight
So whatever value was stored inside of ChangeHeight (or Returned), Gets handed over to theNewHeight variable.
You can then set the height of the picture box:
PictureBox1.Height = NewHeight
When you add that line above, your Button code should look like this:
Notice the last line:
objAlterPicBox = Nothing
Because objects take up space in memory, you can release them by setting the object to Nothing. VB is supposed to do the cleaning up for you, but you can't be sure that it's doing its job properly. So it's good form to release your own objects from memory.
When you've finished adding the code, run your programme and test it out. Click your new button and the Height of the picture box should change.

So just to recap:

  • You set up a Property by using the following code stub:
Public Property PropertyName() As VaraibleType
End Get
Set(ByVal Value As Integer)
End Set
End Property
  • The Set Statement is for setting values for your properties
  • The Get Statement is for returning values from your properties
  • Once you’ve created a new object variable to use you class, type the name of the variable and select your property from the pop up list
  • When you’re setting values for your property, the object variable and property go on the left hand side of the equals sign
ObjectVariableName.PropertyName= PropertyValue
  • When you’re getting values from your property, the object variable and property go on the right hand side of the equals sign
VariableName = ObjectVariableName.PropertyName
  • Release your objects from memory by using the Nothing keyword

OK, that’s just about it for this introduction to Classes and Objects. There’s an awful lot more to learn about Objects, but as a beginner you have learned the fundamentals.. Before you leave this topic, try this exercise:

Exercise O

Set up a property that changes the width of the Picture Box on your Form. Get the new width from the second textbox on your Form.

In the next section, we take a look at VB .NET and Databases.