Constants

Introduction

A constant is a value that doesn't change. There are two types of constants you will use in your programs: those supplied to you and those you define yourself.

To create a constant to use in your program type the Const keyword followed by a name for the variable, followed by the assignment operator "=", and followed by the value that the constant will hold. Here is an example:

Module Exercise
    Sub Main()
        Dim DateOfBirth = #12/5/1974#

        Console.WriteLine(DateOfBirth)
    End Sub
End Module

When defining a constant like this, the compiler would know the type of data to apply to the variable. In this case the DateOfBirth constant holds a Date value. Still, to be more explicit, you can indicate the type of value of the constant by following its name with the As keyword and the desired data type. Based on this, the above program would be:

Module Exercise
    Sub Main()
        Dim DateOfBirth As Date = #12/5/1974#

        Console.WriteLine("Date of Birth: " & DateOfBirth)
    End Sub
End Module

When creating a constant, if its value supports a type character, instead of using the As keyword, you can use that type character. Here is an example:

Module Exercise	

    Sub Main()
        Dim Temperature% = 52
    End Sub

End Module

As mentioned earlier, the second category of constants are those that are built in the Visual Basic language. Because there are many of them and used in different circumstances, when we need one, we will introduce and then use it.

Practical LearningPractical Learning: Using Constants

  1. Start Microsoft Visual Studio
  2. Create a Console App named GeorgetownDryCleaningServices2
  3. In the Solution Explorer, under GeorgetownDryCleaner2, right-click Module1.vb and click Rename
  4. Type CleaningOrder.vb and press Enter
  5. To deal with new dates and times, change the program as follows:
    Module CleaningOrder
        Sub Main()
            Const UnitPriceShirts As Double = 1.25
            Const UnitPricePants As Double = 1.95
            Const UnitPriceOtherItems As Double = 3.25
            Const TaxRate As Double = 5.75
    
            Console.WriteLine("====================================================")
            Console.WriteLine(vbTab & "-/- Georgetown Dry Cleaner -/-")
            Console.WriteLine("====================================================")
            ' Request order information from the user
            Console.Write("Enter Customer Name:          ")
            Dim CustomerName As String = Console.ReadLine()
            Console.Write("Enter Customer Phone:         ")
            Dim CustomerPhone As String = Console.ReadLine()
            Console.Write("Enter the order date:         ")
            Dim OrderDate As Date = Console.ReadLine()
            Console.Write("Enter the order time:         ")
            Dim OrderTime As Date = Console.ReadLine()
    
            Console.Write("Enter Number of Shirts:       ")
            Dim NumberOfShirts As UInteger = Console.ReadLine()
            Console.Write("Enter Number of Pants:        ")
            Dim NumberOfPants As UInteger = Console.ReadLine()
            Console.Write("Enter Number of Other Items:  ")
            Dim NumberOfOtherItems As UInteger = Console.ReadLine()
    
            ' Perform the necessary calculations
            Dim SubTotalShirts As Double = NumberOfShirts * UnitPriceShirts
            Dim SubTotalPants As Double = NumberOfPants * UnitPricePants
            Dim SubTotalOtherItems As Double = NumberOfOtherItems * UnitPriceOtherItems
            ' Calculate the "temporary" total of the order
            Dim TotalOrder As Double = SubTotalShirts + SubTotalPants + SubTotalOtherItems
    
            ' Calculate the tax amount using a constant rate
            Dim TaxAmount As Double = TotalOrder * TaxRate / 100
            ' Add the tax amount to the total order
            Dim NetTotal As Double = TotalOrder + TaxAmount
    
            ' Communicate the total to the user...
            Console.WriteLine("The Total order is:           " & NetTotal)
            ' and request money for the order
            Console.Write("Amount Tended?                ")
            Dim AmountTended As Double = Console.ReadLine()
    
            Console.WriteLine("====================================================")
            Console.WriteLine(vbTab & "-/- Georgetown Dry Cleaner -/-" & vbCrLf &
                   "====================================================" & vbCrLf &
                   vbTab & "Customer Name:    " & CustomerName & vbCrLf &
                   vbTab & "Customer Phone:   " & CustomerPhone & vbCrLf &
                   vbTab & "Order Date:       " & OrderDate & vbCrLf &
                   vbTab & "Order Time:       " & OrderTime & vbCrLf &
                   "====================================================" &
                    vbCrLf & "Item Type" & vbTab & "Qty" & vbTab & "Unit/Price" & vbTab & "Sub-Total" & vbCrLf &
                   "----------------------------------------------------" & vbCrLf &
                   "Shirts " & vbTab & vbTab & NumberOfShirts & vbTab & UnitPriceShirts & vbTab & vbTab & SubTotalShirts & vbCrLf &
                   "Pants " & vbTab & vbTab & NumberOfPants & vbTab & UnitPricePants & vbTab & vbTab & SubTotalPants & vbCrLf &
                   "Other Items " & vbTab & NumberOfOtherItems & vbTab & UnitPriceOtherItems & vbTab & vbTab & SubTotalOtherItems & vbCrLf &
                   "---------------------------------------------------" & vbCrLf & vbTab & vbTab &
                   "Total Cleaning: " & vbTab & TotalOrder & vbCrLf & vbTab & vbTab &
                   "Tax Rate: " & vbTab & vbTab & TaxRate & "%" & vbCrLf & vbTab & vbTab &
                   "Tax Amount: " & vbTab & vbTab & TaxAmount & vbCrLf & vbTab & vbTab &
                   "Net Price: " & vbTab & vbTab & NetTotal & vbCrLf &
                   "===================================================")
        End Sub
    
    End Module
  6. To execute the program, on the main menu, click Debug -> Start Debugging
  7. Enter values as follows:
     
    Customer Name: Jeannette Sharma
    Customer Phone: (301) 218-9000
    Order Date: 04/11/2008
    Order Time 08:24
    Number of Shirts: 6
    Number of Pants: 4
    Number of Other Items: 2
     
    ====================================================
            -/- Georgetown Dry Cleaner -/-
    ====================================================
    Enter Customer Name:          Jeannette Sharma
    Enter Customer Phone:         (107) 493-8074
    Enter the order date:         04/11/2026
    Enter the order time:         08:24
    Enter Number of Shirts:       6
    Enter Number of Pants:        4
    Enter Number of Other Items:  2
    The Total order is:           23.0535
    Amount Tended?                25
    ====================================================
            -/- Georgetown Dry Cleaner -/-
    ====================================================
            Customer Name:    Jeannette Sharma
            Customer Phone:   (107) 493-8074
            Order Date:       4/11/2026
            Order Time:       8:24:00 AM
    ====================================================
    Item Type       Qty     Unit/Price      Sub-Total
    ----------------------------------------------------
    Shirts          6       1.25            7.5
    Pants           4       1.95            7.8
    Other Items     2       3.25            6.5
    ---------------------------------------------------
                    Total Cleaning:         21.8
                    Tax Rate:               5.75%
                    Tax Amount:             1.2535
                    Net Price:              23.0535
    ===================================================
    
    Press any key to close this window . . .
  8. Return to your programming environment

Modules

Introduction

In the small programs we have created so far, we were using only one file. A typical application uses as many files as necessary. You can use one file to list some objects used in other files. As we move on, we will see different examples of creating different files in the same program.

In the Visual Basic language, a file that holds Visual Basic code is called a module.

Creating a Module

As mentioned above, a module is primarily a file that holds code. Therefore, there is no complication with creating one. It is simply a file that holds the .vb extension. If you create a console application using the Console Application option of the New Project dialog box, Microsoft Visual Studio would create a default file for and would insert the module template code.

To create a module in Microsoft Visual Studio or Microsoft Visual Basic 2008 Express Edition, on the main menu, you can click Project -> Add Module... This would display the Add New Item dialog box with the Module selected as default in the Templates list. The studio would also suggest a default name. You can accept that name or change it. The name of the module follows the rules of an object in the Visual Basic language. Once you are ready with the dialog box, you can click Add.

If you are manually creating your code from Notepad or any text editor, you can simply create any file in your folder and give it the .vb extension.

Probably the most important thing in a module is that the area that contains its code must start with a Module ModuleName and end with an End Module line:

Module ModuleName

End Module

Anything between these two lines is part of the normal code and everything that is normal code of the module must be inserted between these two lines. No code should be written outside of these two lines.

After creating a module and adding its required two lines, you can add the necessary code. Of course, there are rules you must follow. At a minimum, you can declare one or more variables in a module, just as we have done so far. Here is an example:

Module Exercise
    Dim FullName As String
End Module

Accessing or Opening a Module

Each module of a project is represented in the Solution Explorer by a name under the project node. To open a module using the Solution Explorer:

If there are many opened module, each is represented in the Code Editor by a label and by an entry in the Windows menu. Therefore, to access a module:

Renaming a Module

As you may have realised, when you start a console application, Microsoft Visual Basic creates a default module and names it Module1. Of course, you can add as many modules as necessary. At any time, you can change the name of a module.

To rename a module, in the Solution Explorer

Deleting a Module

If you have a module you don't need anymore, to delete it, in the Solution Explorer, right-click it and click Delete. You will receive a warning to confirm your intentions or to change your mind.

Access Modifiers

Introduction

As mentioned already, you can use more than one module in a project and you can declare variables in a module. This allows different modules to exchange information. For example, if you are planning to use the same variable in more than section of your application, you can declare the variable in one module and access that variable in any other module in the application.

The Friendly Members of a Module

A variable that is declared in one module and can be accessed from another module in the same application is referred to as a friend. Variables are not the only things that can benefit from this characteristic. We will see other types.

To declare a friendly variable, instead of Dim, you use the Friend keyword. Here is an example:

Module Exercise
    Friend FullName As String
End Module

After declaring such a variable, you can access it from any module of the same application. Here is an example:

File 1: Module1.vb
Module Exercise
    Friend FullName As String
End Module
 
File 2: Exercise.vb
Module Exercise
    Sub Main()
        FullName = "Gertrude Monay"
        Console.WriteLine("Full Name: " & FullName)
    End Sub
End Module

The Private Members of a Module

Instead of allowing a member of a module to be accessible outside the module, you may want to restrict  this access. The Visual Basic language allows you to declare a variable that can be accessed only within the module that contains it. No code outside the module would be able to "see" such a member. A member inside a module and that is hidden from other modules is referred to as private.

To declare a private variable, instead of Dim or Friend, you use the Private keyword. Here is an example:

Module Exercise
    Friend FullName As String
    Private DateHired As Date

    Sub Main()
        FullName = "Gertrude Monay"
        DateHired = #4/8/2008#
        Dim Information As String

        Information = "Full Name: " & FullName &
                      vbCrLf &
                      "Date Hired: " & DateHired
        Console.WriteLine(Information)
    End Sub

End Module

This would produce:

Private

Practical LearningPractical Learning: Declaring Global Private Variables

  1. Change the document as follows:
    Module CleaningOrder
    
        Dim UnitPriceShirts As Double = 1.25
        Dim UnitPricePants As Double = 1.95
        Dim UnitPriceOtherItems As Double = 3.25
        Dim TaxRate As Double = 5.75
    
        Private CustomerName As String, CustomerPhone As String
        Private OrderDate As Date, OrderTime As Date
        ' Unsigned numbers to represent cleaning items
        Private NumberOfShirts As UInteger, NumberOfPants As UInteger
        Private NumberOfOtherItems As UInteger
        ' Each of these sub totals will be used for cleaning items
        Private SubTotalShirts As Double, SubTotalPants As Double
        Private SubTotalOtherItems As Double
        ' Values used to process an order
        Private TotalOrder As Double, TaxAmount As Double
        Private NetTotal As Double
        Private AmountTended As Double
    
        Sub Main()
            ' Request order information from the user
            CustomerName = InputBox("Enter Customer Name:")
            
    	. . . No Change
            
        End Sub
    
    End Module
  2. To execute the program, on the Standard toolbar, click the Start Debugging button Start Debugging
  3. Enter values as follows:
     
    Customer Name: Landry Kurtzmann
    Customer Phone: (202) 223-3325
    Order Date: 04/12/2008
    Order Time 07:35
    Number of Shirts: 8
    Number of Pants: 2
    Number of Other Items: 0
  4. Enter the amount tended as 50
  5. Close the message box and return to your programming environment

The Public Members of a Module

When working on a project, you may want to create objects or declare variables that you want to be accessible from other applications. Such a member is referred to as public.

To declare a variable that can be accessed by the same modules of the same project and modules of other projects, declare it using the Public keyword. Here is an example:

Module Exercise
    Friend FullName As String
    Private DateHired As Date
    Public HourlySalary As Double

    Sub Main()
        FullName = "Gertrude Monay"
        DateHired = #4/8/2008#
        HourlySalary = 36.75
        Dim Information As String

        Information = "Full Name: " & FullName & vbCrLf &
                      "Date Hired: " & DateHired & vbCrLf &
                      "Hourly Salary: " & HourlySalary
        Console.WriteLine(Information)
    End Sub
End Module

This would produce:

Public

Access Modifiers and Modules

The Friend, Private, and Public keywords are called access modifiers because they control the level of access that a member of a module has. In previous sections, we saw how to control the members of a module. The level of access of a module itself can also be controlled. To control the level of access of a module, you can precede the Module keyword with the desired access modifier.

The access modifier of a module can only be either Friend or Public. Here are examples:

File 1: Module1.vb
Friend Module Exercise
    
End Module
 
File 2: Module2.vb
Public Module Exercise
    
End Module

Practical LearningPractical Learning: Access Modifying a Module

  1. Change the document as follows:
    Public Module CleaningOrder
    
        . . . No Change
    
    End Module
  2. On the Standard toolbar, click the Start button Start Debugging
  3. Enter values as follows:
     
    Customer Name: William Nessif
    Customer Phone: (301) 220-3737
    Order Date: 04/12/2008
    Order Time 08:26
    Number of Shirts: 3
    Number of Pants: 3
    Number of Other Items: 3
  4. Enter the amount tended as 40
  5. Close the message box and return to your programming environment

Details on Declaring Variables

Declaring a Series of Variables

Because a program can use different variables, you can declare each variable on its own line. Here are examples:

Module Exercise
    Sub Main()
        Dim NumberOfPages As Integer
        Dim TownName As String
        Dim MagazinePrice As Double
    End Sub
End Module

It is important to know that different variables can be declared with the same data type as in the following example:

Module Exercise
    Sub Main()
        Dim NumberOfPages As Integer
        Dim Category As Integer
        Dim MagazinePrice As Double
    End Sub
End Module

When two variables use the same data type, instead of declaring each on its own line, you can declare two or more of these variables on the same line. There are two techniques you can use: