Basic Structure of Visual Basic

As previously mentioned, Visual Basic is an Object-Oriented Programming (OOP) Language. Object-Oriented Programming is based around the concept of Objects, where an Object is made up of Attributes, or Variables, that can contain data, and Methods, which describe actions of an Object. A person can be used as a real-world example of an Object. A person has Attributes such as height, weight, eye colour, hair colour and so on, as well as Methods or actions such as, walk, talk and eat.

A Class is a blue print, or template, of an Object that describes its Attributes and Methods. From this template, multiple Objects can be created. A Class can be compared to an architects drawing of a building, which describes how it needs to be built. From this drawing, one or more buildings can be made to the specification of the drawing.

The basic structure of a Visual Basic Class can be seen below. A Visual Basic program can contain one or more Classes. Within a Class or Classes of a program, there must be one Class with a Method called ‘Main’, which is executed when the program starts.

' Class definition.
Public Class Class_name

    ' Main method of a Visual Basic application.
    ' Executes when the application starts.
    Public Shared Sub Main()

        ' Statement(s) to execute.

    End Sub

End Class

The words in blue in the above example are known as reserved words and have a specific meaning in Visual Basic. These words cannot be used for anything other than the purpose that the language defines. The green lines of text, preceded by a single quote, are comments. When programming in any language it is useful to add comments to the code to describe what is happening and why. This is useful when the code is revisited at a later date to make enhancements, or for debugging purposes.

The Class below is a simple example of a program that just outputs the message ‘Hello World!’ in a console window. The second line forces the user to press a key on the keyboard before the console window closes.

Public Class Demo

    Public Shared Sub Main()

        Console.WriteLine("Hello World!")
        Console.ReadKey()

    End Sub

End Class

In order to run a program like the one above, you must first compile it. This process can vary depending on what you are using to create the program. If you are using Microsoft Visual Studio, compiling and running a program can be done together using the ‘Start’ button.