VB.Net Tutorial

VB.Net Tutorial #6

Welcome to the sixth VB.Net tutorial (still haven't found a better way to start these tutorials). Now we are getting to the nitty gritty and to the heart of VB.net with the introduction of classes. Now it has to be said that up till now I have not been a big fan of classes but they are growing on me and they are implemented quite nicely in VB.Net unlike older versions. So what is the big mystery? What ARE classes? Well, I've already given you a big clue in the previous tutorial. A Class is a mixture of structures (struct) and functions in one construct. Here is what a simple class looks like with its calling program:-

Imports System

Public Class HelloWorld
	Public i As Integer = 1

	Public Sub ShowHello()
		Console.WriteLine("Hello World with Classes!")
	End Sub
End Class 

Public Class TestHello

	Public Shared Sub Main()
		Dim hw As HelloWorld = New HelloWorld
		hw.ShowHello
		Console.WriteLine(hw.i)
		hw.i = 2
		Console.WriteLine(hw.i)
	End Sub
End Class 

I think I need to explain first that the class TestHello is there just contain the Main() program otherwise it won't compile. What I have done is create my own class outside of the Main() class (and could be contained inside another file) which I can call upon from the Main() program. I can create an instance of it and call functions housed within it. I can also modify variables contained within it much like in a struct. All very clever.

So when should you use classes? Well, you could program in VB.Net and NEVER use them but you would be missing out on a whole lot of stuff. I'm not going into classes any more deeply at this stage but there are some things you ought to know about classes.

It is my aim in these tutorials to teach you enough to be able to use databases and Windows GUI forms and you don't necessarily need all the extra stuff to do it but I may return this subject in later tutorials. Here is an enhancement to the above program:-

Imports System

Public Class HelloWorld
	Public i As Integer = 1

	Public Sub ShowHello()
		Console.WriteLine("Hello World with Classes!")
	End Sub
End Class 

Public Class ShowTime

	Public Sub ShowCurrentTime()
		Console.WriteLine("The current time is: " + DateTime.Now)
	End Sub
End Class 

Public Class TestHello

	Public Shared Sub Main()
		Dim hw As HelloWorld = New HelloWorld
		hw.ShowHello
		Console.WriteLine(hw.i)
		hw.i = 2
		Console.WriteLine(hw.i)
		Dim st As ShowTime = New ShowTime
		st.ShowCurrentTime
	End Sub
End Class 

This enables you to call a class to get the current time.

I was babbling on in earlier tutorials about how classes can combine both structures and functions. Here's how:-

Imports System

Class clsPhone
	Private strName As String
	Private strNumber As String

	Sub AddPhone()
		strName = "Nick"
		strNumber = "01234567890"
	End Sub

	Shared Sub Main()
		Dim pb As clsPhone = New clsPhone
		pb.AddPhone
		Console.WriteLine(pb.strName)
		Console.WriteLine(pb.strNumber)
	End Sub
End Class 

Here we can create an instance of a data sturcture and add data as if it were a structure and run functions that can do the update if required. I hope that all this will become clearer as we move further into these tutorials. So thats it with classes. Having alluded to the fact that structures are the building blocks for creating databases, to complete such an application, you need to be able to save the information to disk and for that you need files. You need to be able to do the following things with files:-

Here is a sample program:-

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Dim strPath As String = "Test.txt"
        Dim sw As StreamWriter

        ' Create file
        If File.Exists(strPath) = False Then
            sw = File.CreateText(strPath)

            sw.WriteLine("Hello")
            sw.Flush()
            sw.Close()
        End If

	' append to file
        sw = File.AppendText(strPath)
        sw.WriteLine("Welcome")
        sw.Flush()
        sw.Close()

        ' Read file
        Dim sr As StreamReader = File.OpenText(strPath)
        Dim s As String
        Do While sr.Peek() >= 0
            s = sr.ReadLine()
            Console.WriteLine(s)
        Loop
        sr.Close()
    End Sub
End Class

This isn't everything as you need to be able to update individual records within files but that is really beyond the scope of these tutorials as I'm sure you're itching to get to databases proper which does all this for you so I'll leave it at that. The above program is in three sections. The first sets the file name to the current directory and if the file doesn't exist then create a text file and write a line to it. It isn't necessary to close a file in C# but it has to be done in visual basic. The second section appends a line of text to an existing file and the third reads it (using SteamReader rather than StreamWriter) and writes the contents to the screen until the end of the file is reached.

That wraps up files. One other thing to aquaint you with (yes databases is next!) is error checking. This is done using try, catch, finally which has been part of C++ and Java for a while but has made it into VB.net (and C#.Net as well). Heres some code:-

Imports System

Public Class ExceptionTest

	Public Shared Sub Main()
		Try
			Console.WriteLine("Try")
			Dim a As Integer = 0
			Dim b As Integer = 100 / a
		Catch e As Exception
			Console.WriteLine("Catch")
			Console.WriteLine(e.Message)
		Finally
			Console.WriteLine("Finally")
		End Try
	End Sub
End Class 

It was quite difficult to find a simple bit of code to trip an exception (error to you) but here is a divide by zero error sample. The code we want to use goes inside the try section which would usually be some kind of open command which may trip an error if a file doesn't exist for example. If an error is generated then the catch part comes into play and generates an error message. The finally bit ALWAYS runs and would normally contain the file close command so the file would be closed no matter what. We will need this in the next tutorial (which will be databases...honest). See you then...

Back to VB.net Tutor

Written by Nick Cheesman. Last updated: 01/06/2007
Please eMail me at:
nickjc@nickjc.co.uk