Home

Introduction to Classes

 

Programmer-Defined Types

 

Introduction

In previous lessons, we used individual variables whenever we needed them. This allowed us to declare simple types to hold fairly small values. In the Visual Basic language, you can combine a group of variables into an entity. These variables become considered as one. You can then declare one or more elaborate variables from this enhanced type. Such a new type is called a class.

HomePractical Learning: Introducing Classes

  1. Start Microsoft Visual Basic and create a console application
  2. In the empty file, type the following:
     
    Imports System
    
    Module Exercise
    
        Sub Main()
        
        End Sub
    
    End Module
  3. To save the file, on the main menu click File -> Save
  4. Locate your VBasic folder and display it in the Save In combo box
  5. Click the Create New Folder button on the toolbar of the Save As dialog box
  6. Type DeptStore1 as the name of the new folder and press Enter twice to display it in the Save In combo box
  7. Change the Save As Type combo box to All Files
  8. Set the name of the file to Exercise.vb and click Save

Creating a Class

Imagine you want to represent a rectangle as a geometric object:

You can declare each of its various parts as a variable. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim RectLength As Double
        Dim RectHeight As Double

        RectLength = 24.55 : RectHeight = 20.75

        MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _
               	     "Length: " & vbTab & RectLength & vbCrLf & _
                     "Height: " & vbTab & RectHeight)

        Return 0
    End Function

End Module

This would produce:

Class

If you want to treat the whole rectangle as one object, you can create a class for it. To create a class, you can use the Class keyword followed by a name. The name of a class follows the rules we have applied so far for variable and function names. To declare a class called Rectangle, you would start with the following:

Class Rectangle

As a name that represents a group of items, a class has a body that would be used to define the items that compose it. The body of a class starts after its name. 

To indicate the end of the class, type End Class. Therefore, a class can be created as follows:

Class Rectangle

End Class

Since a class is a combination of other variables, you declare each variable inside of the body of the class. Each item that composes the class is represented as a complete variable declared with a name and a data type. By adding a Length and a Height variables, our class would become: 

Class Rectangle
    Dim Length As Double
    Dim Height As Double
End Class

The items that compose a class are called members of the class. When creating the members of a class, you can omit the Dim keyword:

Class Rectangle
    Length As Double
    Height As Double
End Class

To create a class in Microsoft Visual Basic:

  1. On the main menu, you can click Project -> Add Class... Alternatively, in the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click Class
  2. In the Templates section of the Add New Item dialog box, make sure the Class item is selected. Accept the suggested name or replace it in the Name text box
     
  3. Click Add

HomePractical Learning: Introducing Class Members

Imagine you want to write a (console-based) program for a department store and the customer has given you a preliminary catalog as follows:

Stock #: 437876
Women Spring Coat Classy
Unit: $145.55
Stock #: 79475
Women Bathing Suit Sandstone
$75.55
Stock #: 74797
Women Suit Exchange
$225.75
Stock: 68432
Men Jacket
$115.85
Stock #: 75947
Children Summer Hat
$17.95
Stock #: 48746
Children Playground Dress
$24.55

Each item in this catalog is represented by its Stock number, its name or description, and its price. Based on this, you can create a class that represents each item.

  1. In the document, create a DepartmentStore class as follows:
     
    Imports System
    
    Module Exercise
    
        Class DepartmentStore
            Dim ItemNumber As Long
            Dim ItemName As String
            Dim UnitPrice As Double
        End Class
    
        Sub Main()
        
        End Sub
    
    End Module
  2. Save the file

Accessing a Class

A common object in real life is visibly made of two categories of parts: those you can see or touch and those you do not have access to. The parts you can see or touch are considered visible or accessible. A parts that is visible is referred to as public. A part you cannot see or touch are considered hidden, also referred to as private. Like objects in real life, a class is made of members that the other parts of a program cannot “see” and those the other parts of a program can access. The other parts of a program are sometimes referred to as clients. The parts a client can see in a class are considered public and the others are private.

When creating a class, you will define what members are public and which ones are private. The members that are public are preceded by Public keyword. The others are preceded by the Private keyword. If you don't specify an access level of a member of a class, the member is considered private. Based on this, both members of the TRectangle class created above are private. To make them public, the class can be created as follows:

Class TRectangle
    Public Length As Double
    Public Height As Double
End Class

The public and private keywords are referenced by their access level because they control how much access a variable allows. 

HomePractical Learning: Controlling the Access Level

  1. To specify the member variables as public, change the file as follows:
     
    Imports System
    
    Module Exercise
    
        Class DepartmentStore
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
        End Class
    
        Sub Main()
            
        End Sub
    
    End Module
  2. Save the file 

Sharing a Class

Although you may think of working only in Visual Basic .NET, in some cases, you may create a class and need to share it with code written in another language such as C++/CLI or C#, to make this possible, you can give "public" access to your class.

If you want your class to be accessible to code written in other languages, precede the class keyword with Public when creating it. Here is an example:

Public Class TRectangle
    Length As Double
    Height As Double
End Class

A Program With Various Files

Instead of only one file, you can create a program with many of them. Each file can contain different assignments that, when put together, can create an application as complete as possible. To make this possible, you can create each file with a name and the extension .vb. To compile the project, after typing vbc, you can list the files separated by commas.

 

Declaring a Variable of a Class

After creating a class, to use it in a program, you can declare it as a variable. Unlike variables declared from primitive types as we have done so far, a class must be declared as a reference. This is done by assigning the New keyword followed by the name of the class to the declared variable. For example, do declare a variable of the above TRectangle class, you would type the following:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        Dim Recto As New TRectangle

    End Sub

End Module

Period: .

To access the property of an object, type the name of the object, followed by a period, followed by the name of the property you need. The property you are trying to use must be part of the properties of the object.

If you know the name of the property, you can start typing it. Once the desired property is highlighted, press the Space bar or Tab. If you see the name of the property in the list, you can double-click click it. If the list doesn't appear, press Ctrl + Space bar. If you don't want to use the list displayed by the Code Editor, press Esc. Once you have specified what property you want to use, you can assign it the desired value or you can involve it in any operation you see fit.

A variable declared of a class is also called an object. When an object has been created, you can access any of its members using the period operator ".". First, type the name of the object, followed by a period, followed by the name of the member you want to access. For example, to access the Length member of the above class, you would write:

Recto.Length

Using this syntax, you can display the value of a class member. Here are examples:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        Dim Recto As New TRectangle

        Recto.Length = 24.55 : Recto.Height = 20.75

        Console.WriteLine("=-= Rectangle Characteristics =-=")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)

        Console.WriteLine()
    End Sub

End Module

Here is an example of running the program:

=-= Rectangle Characteristics =-=
Length:    24.55
Height:    20.75

You can also request the values of the members of a class from the user. Here is an example:

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        Dim Recto As New TRectangle

        Console.Write("Enter Rectangle Length: ")
        Recto.Length = Console.ReadLine()
        Console.Write("Enter Rectangle Height: ")
        Recto.Height = Console.ReadLine

        Console.WriteLine()
        Console.WriteLine("=-= Rectangle Characteristics =-=")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)

        Console.WriteLine()
    End Sub

End Module

You can also involve the members of a class in any operation you see fit, even if the other operands are locally declared variables or constant values as in the following code:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        im Recto As New TRectangle
        Dim Perimeter As Double
        Dim Area As Double


        Console.Write("Enter Rectangle Length: ")
        Recto.Length = Console.ReadLine()
        Console.Write("Enter Rectangle Height: ")
        Recto.Height = Console.ReadLine

        Perimeter = (Recto.Length + Recto.Height) * 2
        Area = Recto.Length * Recto.Height

        Console.WriteLine()
        Console.WriteLine("Rectangle Characteristics")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)
        Console.WriteLine("Perimeter: {0}", Perimeter)
        Console.WriteLine("Area:      {0}", Area)

        Console.WriteLine()
    End Sub

End Module

Here is an example of running the program:

Enter Rectangle Length: 32.48
Enter Rectangle Height: 28.64

Rectangle Characteristics
Length:    32.48
Height:    28.64
Perimeter: 122.24
Area:      930.2272

 

 

Practical LearningPractical Learning: Declaring a Class Variable

  1. To use the DepartmentStore class in the main class of the project, change the file as follows:
     
    Imports System
    
    Module Exercise
    
        Public Class DepartmentStore
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
        End Class
    
        Sub Main()
            Dim dptStore As DepartmentStore = New DepartmentStore
    
            dptStore.ItemNumber = 737853
            dptStore.ItemName = "Men's Tie"
            dptStore.UnitPrice = 35.95
    
            Console.WriteLine("Department Store")
            Console.WriteLine("Item #:     {0}", dptStore.ItemNumber)
            Console.WriteLine("Item Name:  {0}", dptStore.ItemName)
            Console.WriteLine("Unit Price: {0}", dptStore.UnitPrice)
        End Sub
    
    End Module
  2. Save the Exercise.vb file and open the Command Prompt
  3. Switch to the folder that contains the above file
  4. Compile it by typing vbc Exercise.vb and pressing Enter
  5. Execute it by typing Exercise and pressing Enter. This would produce:
     
     
  6. Return to Notepad

 

Namespaces

 

Introduction

A namespace is a section of code that is recognized with a name. Namespaces were created to allow each programmer or a group of programmers who work with others to create code with names that don't conflict with code of the other programmers or other groups. Based on their usefulness, namespaces have become highly used.

Accessing Members of a Namespace

To access an item that is part of the namespace, you can use the period operator. To do this, in the desired location, type the name of the namespace, followed by a period, followed by the desired member of the namespace. For example, if you had a namespace named Accounting and it contains a member named Departure, to access this member, you would type the following:

Accounting.Departure

The System Namespace

To make programming in Visual Basic easier, many classes were created and stored in various namespaces. Each namespace is used to provide specific instructions. The most regularly used namespace in Visual Basic is called System. Inside of the System namespace is a class called Console. The Console class is used to display things on the console screen also called the DOS window.

The Console class contains procedures to display information on the screen or to retrieve information from the user who types it in the DOS window. The procedure that is used to display text on the screen is called Write. To use Write(), inside of the parentheses, type the sentence between double-quotes.

Besides Write(), the Console class also provides a procedure called WriteLine(). The difference is that, after displaying something on the screen, the Write() method keeps the caret on the same line but WriteLine() transfers the caret to the next line.

 

Importing a Namespace

We mentioned that, to access a member of a namespace, you could type the name of the namespace, followed by a period, and followed by the name of the member. This technique is referred to as qualifying a member of a namespace. This can be long ins some cases. Instead of qualifying a member of a namespace every time you want to use it, you can import the namespace into the file where you want to access its member(s). To import a namespace, type the Imports keyword in the top section of the file, followed by the name of the namespace.

Practical LearningPractical Learning: Importing a Namespace

  1. Return to Notepad and change the program as follows:
     
    Imports System
    
    Module Exercise
        Sub Main()
            Console.WriteLine("Welcome to the Wonderful World of VBasic")
        End Sub
    End Module
  2. Save the file and return to the Command Prompt
  3. To compile the exercise, type vbc exercise.vb and press Enter
  4. To execute the application, type exercise and press Enter
  5. Return to Notepad

 

Introduction to Libraries

A library is code that can be used by programmers without knowing how the library was created. The only important information about the library is to know what it offers and how its contents can be used to complement a program. Microsoft created a huge library called the .NET Framework. You need this library to create Visual Basic applications. As mentioned earlier, you may have it already installed in your computer. Otherwise, you can download it from the Microsoft web site.

Home

The Methods of a Class

 

Introduction

The variables of a program cannot perform assignments. In the same way, the member variables of a class can initiate nor perform actions. So far, we were using procedures to do that. In the same way, to create a class as complete as possible, you can equip it with its own procedures. Such a procedure is created as a member of the class.

A procedure that is made a member of a class is also called a method. Throughout these lessons, the word method will be used as a procedure (Sub or Function) that is a member of a class.

 

Creating Methods

Like a normal procedure, a method can be made to return a value, in which case it would be a function. To create a method as a function, use the same techniques we have used so far to create a function. Here is an example:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double

        Function Perimeter() As Double

        End Function
    End Class

    Sub Main()
        
    End Sub

End Module

A method can also be created not to return a value, making a sub procedure.

After declaring a procedure, in its body, you can implement the expected behavior. When a method has been created, it has access to all of the other members of the same class. This means that you don't have to re-declare a member of a class to access it in a method. Based on this, you can manipulate any member variable of the same class as you wish. Like the member variables, the methods can be accessed outside of the class using the period operator. Here is an example:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double

        Function Perimeter() As Double
            Return (Length + Height) * 2
        End Function
        Function Area#()
            Return Length * Height
        End Function
    End Class

    Sub Main()
        Dim Recto As New TRectangle
        Dim Perimeter As Double
        Dim Area As Double

        Console.Write("Enter Rectangle Length: ")
        Recto.Length = Console.ReadLine()
        Console.Write("Enter Rectangle Height: ")
        Recto.Height = Console.ReadLine

        Console.WriteLine()
        Console.WriteLine("Rectangle Characteristics")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)
        Console.WriteLine("Perimeter: {0}", Recto.Perimeter)
        Console.WriteLine("Area:      {0}", Recto.Area)

        Console.WriteLine()
    End Sub


End Module
 

Practical LearningPractical Learning: Creating Methods of a Class

  1. To add two methods of the class, change the file as follows:
     
    Imports System
    
    Module Exercise
    
        Public Class DepartmentStore
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
    
            Public Sub RegisterStoreItem()
                Console.Write("Enter Item #:     ")
                ItemNumber = CLng(Console.ReadLine())
                Console.Write("Enter Item Name:  ")
                ItemName = Console.ReadLine()
                Console.Write("Enter Unit Price: $")
                UnitPrice = CDbl(Console.ReadLine())
            End Sub
    
            Public Sub ShowItem()
                Console.WriteLine("Item #:     {0}", ItemNumber)
                Console.WriteLine("Item Name:  {0}", ItemName)
                Console.WriteLine("Unit Price: {0}", UnitPrice)
            End Sub
        End Class
    
        Sub Main()
            Dim dptStore As DepartmentStore = New DepartmentStore
    
            Console.WriteLine(" =#=  Department Store =#=")
            Console.WriteLine(" --- Item Registration ---")
            Console.WriteLine("Enter the following pieces of information")
            dptStore.RegisterStoreItem()
    
            Console.WriteLine()
            Console.WriteLine(" =#= Department Store =#=")
            Console.WriteLine(" ---  Store Inventory ---")
            dptStore.ShowItem()
        End Sub
    
    End Module
  2. Save the file and switch to the Command Prompt
  3. Compile and execute the program. Here is an example of running it:
     
     
  4. Return to Notepad
 

Methods and Arguments

Like regular procedures we have used so far, methods of a class can have arguments. The rules are the same as we have applied them so far. When you create a method, it has direct access to all regular members of its class. This means that you don't have to create an argument for a member variable of the same class. You would need an argument only if an external value would be passed to the method.

 

Practical LearningPractical Learning: Creating Argumentative Methods

  1. To create a method that takes arguments, change the file as follows:
     
    Imports System
    
    Module Exercise
    
        Class DepartmentStore
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
    
            Public Sub RegisterStoreItem(ByVal nbr As Long, _
    			ByVal name As String, ByVal price As Double)
                ItemNumber = nbr
                ItemName = name
                UnitPrice = price
            End Sub
    
            Public Sub ShowItem()
                Console.WriteLine("Item #:     {0}", ItemNumber)
                Console.WriteLine("Item Name:  {0}", ItemName)
                Console.WriteLine("Unit Price: {0}", UnitPrice)
            End Sub
        End Class
    
        Sub Main()
            Dim dptStore As DepartmentStore = New DepartmentStore
    
            Dim itmNbr As Long
            Dim itmName As String
            Dim uPrice As Double
    
            Console.Write("Enter Item #:     ")
            itmNbr = CLng(Console.ReadLine())
            Console.Write("Enter Item Name:  ")
            itmName = Console.ReadLine()
            Console.Write("Enter Unit Price: $")
            uPrice = CDbl(Console.ReadLine())
    
            dptStore.RegisterStoreItem(itmNbr, itmName, uPrice)
            dptStore.ShowItem()
        End Sub
    
    End Module
  2. Save the file and switch to the Command Prompt
  3. Compile and execute the application to test it
  4. Return to Notepad
 

Methods Overloading

Just done for regular procedures, the methods of a class can be overloaded. The difference between two overloaded methods must lie on their signature which includes the names of the methods, their arguments, and the numbers of their arguments.

Home

A Class Instance

 

With a Class Instance

After declaring a variable of a class, you can initialize it and access any of its members as you see fit. To initialize an object of a class, we saw that you can access any or each of its public member variables and assign it the appropriate value. Here is an example:

Imports System

Module Exercise

    Enum EmploymentStatus
        esPartTime
        esFullTime
        esContractor
    End Enum

    Class Employee
        Public FirstName As String
        Public LastName As String
        Public Address As String
        Public City As String
        Public State As String
        Public ZIPCode As Long
        Public Gender As Char
        Public EmplStatus As EmploymentStatus
    End Class

    Sub Main()
        Dim Empl As New Employee

        Empl.FirstName = "Emilie"
        Empl.LastName = "Gudson"

        Console.WriteLine("Employee Information")
        Console.WriteLine("Full Name: {0}, {1}", Empl.LastName, Empl.FirstName)

        Console.WriteLine()
    End Sub

End Module

This would produce:

Employee Information
Full Name: Gudson, Emilie

If a class has many members and you want to change the values of many or all of them, you can use the With keyword to type the name of the class variable once. After doing this, use the period operator to access each desired member. Here is an example:

Imports System

Module Exercise

    Enum EmploymentStatus
        esPartTime
        esFullTime
        esContractor
    End Enum

    Class Employee
        Public FirstName As String
        Public LastName As String
        Public Address As String
        Public City As String
        Public State As String
        Public ZIPCode As Long
        Public Gender As Char
        Public EmplStatus As EmploymentStatus
    End Class

    Sub Main()
        Dim Empl As New Employee

        With Empl
            .FirstName = "Emilie"
            .LastName = "Gudson"
            .Address = "824 Lauseanne Ave"
            .City = "Takoma Park"
            .State = "Maryland"
            .ZIPCode = 20910
            .Gender = "F"
            .EmplStatus = EmploymentStatus.esFullTime

            Console.WriteLine("Employee Information")
            Console.WriteLine("Full Name:   {0}, {1}", .LastName, .FirstName)
            Console.WriteLine("Address:     {0}", .Address)
            Console.WriteLine("             {0}, {1}, {2}", .City, .State, .ZIPCode)
            Console.Write("Gender:      ")

            If .Gender = "M" Then
                Console.WriteLine("Gender")
            ElseIf .Gender = "F" Then
                Console.WriteLine("Female")
            Else
                Console.WriteLine("Unknown")
            End If

            Console.Write("Empl Status: ")
            If .EmplStatus = EmploymentStatus.esContractor Then
                Console.WriteLine("Contractor")
            ElseIf .EmplStatus = EmploymentStatus.esFullTime Then
                Console.WriteLine("Full Time")
            Else
                Console.WriteLine("Part Time")
            End If
        End With

        Console.WriteLine()
    End Sub

End Module

This would produce:

Employee Information
Full Name:   Gudson, Emilie
Address:     824 Lauseanne Ave
             Takoma Park, Maryland, 20910
Gender:      Female
Empl Status: Full Time
 

Shared Member Variables

When you declare a variable of a class, you are said to have created an instance of the class. This makes an object available so you can initialize and use its member variables and methods as you see fit.

Just as you can declare one instance of a class, in the same way, you can declare as many instances as you judge it necessary. After declaring various variables of the same class and initializing them, each variable has and keeps its own values. Here is an example:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double

        Function Perimeter#()
            Return (Length + Height) * 2
        End Function

        Function Area#()
            Return Length * Height
        End Function
    End Class

    Sub Main()
        Dim RegistrationCard As New TRectangle
        Dim Invoice As New TRectangle

        RegistrationCard.Length = 24.55 : RegistrationCard.Height = 20.68
        Invoice.Length = 8.5 : Invoice.Height = 11.65

        Console.WriteLine("Paper Registration Characteristics")
        Console.WriteLine("Length:     {0}", RegistrationCard.Length)
        Console.WriteLine("Height:      {0}", RegistrationCard.Height)
        Console.WriteLine("Perimeter: {0}", RegistrationCard.Perimeter)
        Console.WriteLine("Area:         {0}", RegistrationCard.Area)

        Console.WriteLine("Paper Invoice Characteristics")
        Console.WriteLine("Length:    {0}", Invoice.Length)
        Console.WriteLine("Height:     {0}", Invoice.Height)
        Console.WriteLine("Perimeter: {0}", Invoice.Perimeter)
        Console.WriteLine("Area:         {0}", Invoice.Area)
    End Sub

End Module

This would produce:

Paper Registration Characteristics
Length:    24.55
Height:    20.68
Perimeter: 90.46
Area:      507.694

Paper Invoice Characteristics
Length:    8.5
Height:    11.65
Perimeter: 40.3
Area:      99.025

In order to access the member variables of the above TRectangle class, you must declare a variable of the class. Visual Basic provides an alternative. You can declare a member variable so that you can directly access it from anywhere in your code without primarily declaring a variable of the class. In order to have such a member variable, you must explicitly create it as shared.

To create a shared member variable, type the Shared keyword on its left when declaring it. After the shared member variable has been declared, you can use it like any other member variable of that class, except that you don't need to declare an instance of that class when you want to access that member variable. Here is an example:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Shared Height As Double

        Function Perimeter#()
            Return (Length + Height) * 2
        End Function

        Function Area#()
            Return Length * Height
        End Function
    End Class
    Sub Main()
        REM Notice that a TRectangle variable is not declared
        TRectangle.Height = 20.68

        Console.WriteLine("Rectangle Characteristics")
        Console.WriteLine("Height:    {0}", TRectangle.Height)
    End Sub

End Module

This would produce:

Rectangle Characteristics
Height:    20.68

Based on this, when creating a class, you will decide whether you want a particular member variable to be shared or not. You can have only one, two, more, or all member variables shared in a class. Experience and your own goal will guide you.

 

Shared Methods

Consider the following class:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Shared Height As Double

        Function Perimeter#()
            Return (Length + Height) * 2
        End Function

        Function Area#()
            Return Length * Height
        End Function
    End Class

    Sub Main()
        REM Notice that a TRectangle variable is not declared
        TRectangle.Height = 20.68
        TRectangle.Length = 32.47

        Console.WriteLine("Rectangle Characteristics")
        Console.WriteLine("Length:    {0}", TRectangle.Length)
        Console.WriteLine("Height:    {0}", TRectangle.Height)
    End Sub

End Module

This would produce:

Rectangle Characteristics
Length: 32.47
Height: 20.68

Like member variables, a method can be shared among classes. In some cases, shared methods are more used than shared member variables because a shared method allows performing an action on a class without declaring an instance of that class.

To create a shared method, type the Shared keyword on the left of the method's name. Like a shared member variable, once a method has been created as shared, it can be accessed directly from anywhere. Remember that you would need to type the name of the class before accessing the method. The name of the class allows you to "qualify" the method. Here is an example:

Imports System

Module Exercise

    Class TRectangle
        Public Shared Length As Double
        Public Shared Height As Double

        Shared Function Perimeter#()
            Return (Length + Height) * 2
        End Function

        Shared Function Area#()
            Return Length * Height
        End Function
    End Class

    Sub Main()
        REM Notice that a TRectangle variable is not declared
        TRectangle.Height = 20.68
        TRectangle.Length = 32.47

        Console.WriteLine("Rectangle Characteristics")
        Console.WriteLine("Length:    {0}", TRectangle.Length)
        Console.WriteLine("Height:    {0}", TRectangle.Height)
        Console.WriteLine("Perimeter: {0}", TRectangle.Perimeter)
        Console.WriteLine("Area:      {0}", TRectangle.Area)
    End Sub

End Module

 

 

Sharing the Main Method

So far, we were creating the Main() procedure as a Sub. This was a requirement for it when belonging to a module. If you want to create your application from a class, you can include the Main() procedure in such a class. The rule you must observe is that Main() must be created as a shared procedure. Based on this, you can create Main() as follows:

Imports System

Class Exercise

   Shared Sub Main()

      Console.WriteLine("Microsoft Visual Basic .NET Programming Language")

   End Sub

End Class

For the rest of our lessons, we will use either the module or the class version.

 

Me

We have mentioned two techniques of accessing the members of a class, one consisted of declaring a variable of the class, the other had to do with Shared members. None of these techniques is important if you want to access a member variable or method of a class from another method of the same class. We know already that the members of a class are made available to all other members of the same class without being declared or qualified. Consider the following class:

Public Class Triangle
        Public Base As Double
        Public Height As Double
        Public Area As Double

        Public Sub Show()
            Dim Area As Double
            Area = Base * Height / 2
        End Sub
End Class

When the Area variable is used in the Show() method, there are two variables available and named Area. It makes it confusing to know what particular variable is being accessed. You can use a special member of a class that allows you to specify the member of a class when accessing it. This member is called Me.

When using Me, you can access any member of a class within any method of the same class. Here is an example:

Imports System

Class Exercise

    Public Class Triangle
        Public Base As Double
        Public Height As Double

        Public Sub Show()
            Dim Area As Double

            ' Using "this" to access the members of this class
            Me.Base = 24.55
            Me.Height = 20.75

            ' You cannot use this to access Area because Area 
            ' is not a member of this class
            Area = Me.Base * Me.Height / 2

            Console.WriteLine("Triangle Characteristics")
            Console.WriteLine("Base:   {0}", Me.Base)
            Console.WriteLine("Height: {0}", Me.Height)
            Console.WriteLine("Area:   {0}", Area) ' Area is not a member of the Exercise class
        End Sub
    End Class

    Shared Sub Main()
        Dim tri As Triangle = New Triangle
        tri.Show()
    End Sub

End Class

This would produce:

Triangle Characteristics
Base:   24.55
Height: 20.75
Area:    254.70625

There are exceptions when using Me:

  • Me can never be declared: it is automatically implied when you create a class
  • Me cannot be used in a class A to access a member of class B 
  • Me cannot be used in a Shared method. The following program will not compile because Me is used in the Show() method declared as a Shared method:
     
    Imports System
    
    Class Exercise
    
        Public Class Triangle
            Public Base As Double
            Public Height As Double
    
            Public Shared Sub Show()
                Dim Area As Double
    
                ' Using "this" to access the members of this class
                Me.Base = 24.55
                Me.Height = 20.75
    
                ' You cannot use this to access Area because Area 
                ' is not a member of this class
                Area = Me.Base * Me.Height / 2
    
                Console.WriteLine("Triangle Characteristics")
                Console.WriteLine("Base:   {0}", Me.Base)
                Console.WriteLine("Height: {0}", Me.Height)
                Console.WriteLine("Area:    {0}", Area)
            End Sub
        End Class
    
        Sub Main()
            
        End Sub
    
    End Class
 
 
 

Previous Copyright © 2008 Yevol Next