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()
        Const DateOfBirth = #12/5/1974#

        MsgBox(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()
        Const DateOfBirth As Date = #12/5/1974#

        MsgBox("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()
        Const 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 Basic
  2. To create a new application, on the Start Page, click New Project...
  3. In the middle list, click Console Application
  4. In the Name text box, replace the name with GeorgetownDryCleaningServices2
  5. Click OK
  6. In the Solution Explorer, under GeorgetownDryCleaner2, right-click Module1.vb and click Rename
  7. Type CleaningOrder.vb and press Enter
  8. 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
    
            Dim CustomerName As String, CustomerPhone As String
            Dim OrderDate As Date, OrderTime As Date
            ' Unsigned numbers to represent cleaning items
            Dim NumberOfShirts As UInteger, NumberOfPants As UInteger
            Dim NumberOfOtherItems As UInteger
            ' Each of these sub totals will be used for cleaning items
            Dim SubTotalShirts As Double, SubTotalPants As Double
            Dim SubTotalOtherItems As Double
            ' Values used to process an order
            Dim TotalOrder As Double, TaxAmount As Double
            Dim NetTotal As Double
            Dim AmountTended As Double
    
            ' Request order information from the user
            CustomerName = InputBox("Enter Customer Name:")
            CustomerPhone = InputBox("Enter Customer Phone:")
            OrderDate = InputBox("Enter the order date:")
            OrderTime = InputBox("Enter the order time:")
    
            NumberOfShirts = InputBox("Enter Number of Shirts")
            NumberOfPants = InputBox("Enter Number of Pants")
            NumberOfOtherItems = InputBox("Enter Number of Other Items")
    
            ' Perform the necessary calculations
            SubTotalShirts = NumberOfShirts * UnitPriceShirts
            SubTotalPants = NumberOfPants * UnitPricePants
            SubTotalOtherItems = NumberOfOtherItems * UnitPriceOtherItems
            ' Calculate the "temporary" total of the order
            TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOtherItems
    
            ' Calculate the tax amount using a constant rate
            TaxAmount = TotalOrder * TaxRate / 100
            ' Add the tax amount to the total order
            NetTotal = TotalOrder + TaxAmount
    
            ' Communicate the total to the user...
            MsgBox("The Total order is: " & NetTotal)
            ' and request money for the order
            AmountTended = InputBox("Amount Tended?")
    
            MsgBox(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 & CStr(NumberOfShirts) &
               vbTab & CStr(UnitPriceShirts) & vbTab & CStr(SubTotalShirts) & vbCrLf &
                   "Pants " & vbTab & vbTab & CStr(NumberOfPants) & vbTab &
                   CStr(UnitPricePants) & vbTab & CStr(SubTotalPants) & vbCrLf &
                   "Other Items " & vbTab & CStr(NumberOfOtherItems) & vbTab &
                   CStr(UnitPriceOtherItems) & vbTab &
                   CStr(SubTotalOtherItems) & vbCrLf &
                "-----------------------------------------------------------" &
                vbCrLf & vbTab & "Total Cleaning: " & vbTab & CStr(TotalOrder) & vbCrLf &
                   vbTab & "Tax Rate: " & vbTab & CStr(TaxRate) & "%" & vbCrLf &
                   vbTab & "Tax Amount: " & vbTab & CStr(TaxAmount) & vbCrLf &
                   vbTab & "Net Price: " & vbTab & CStr(NetTotal) & vbCrLf &
                   "==============================")
        End Sub
    
    End Module
  9. On the main menu, click Project -> GeorgetownDryCleaningServices2 Properties
  10. Click the arrow of the Application Type box and select Windows Forms Application
  11. Click the Close button Close to close the Property Pages window
  12. To execute the program, on the main menu, click Debug -> Start Debugging
  13. 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
     
  14. Enter the amount tended as 40
     
    Georgetown Dry Cleaner
  15. Close the message box and return to your programming environment

Nothing

So far, to initialize a variable, we were using a known value. Alternatively, you can use the Nothing constant to initialize a variable, simply indicating that it holds a value that is not (yet) defined. Here is an example:

Module Exercise

    Sub Main()
        Dim DateOfBirth As Date = Nothing
    End Sub

End Module

If you use the Nothing keyword to initialize a variable, the variable is actually initialized to the default value of its type. For example, a number would be assigned 0, a date would be assigned January 1, 0001 at midnight.

The Scope and Lifetime of a Variable

Local Variables

 

The scope of a variable determines the areas of code where the variable is available. You may have noticed that, so far, we declared all our variables only inside of Main(). Actually, the Visual Basic language allows you to declare variables outside of Main() (and outside of a particular procedure).

A variable declared inside of a procedure such as Main() is referred to as a local variable. Such as variable cannot be accessed by another part (such as another procedure) of the program.

Global Variables

A variable that is declared outside of any procedure is referred to as global. To declare a global variable, use the same formula as we have done so far. For example, just above the Sub Main() line, you can type Dim, followed by the name of the variable, the As keyword, its type and an optional initialization. Here is an example:

Module Exercise

    Dim DateOfBirth As Date

    Sub Main()
        
    End Sub

End Module

As mentioned above, you can initialize the global variable when or after declaring it. Here are two examples:

Module Exercise

    Dim UnitPrice As Double
    Dim DateOfBirth As Date = #12/5/1974#

    Sub Main()
        UnitPrice = 24.95
        MsgBox("Date of Birth: " & DateOfBirth)
        MsgBox("Unit Price: " & UnitPrice)
    End Sub

End Module

As we will see when studying procedures, a global variable can be accessed by any other procedure (or even class) of the same file. In most cases, a global variable must be declared inside of a module, that is, between the Module ModName and the End Module lines but outside of a procedure. Based on this, such a variable is said to have module scope because it is available to anything inside of that module.

Practical LearningPractical Learning: Declaring Global Constants

  1. Change the document as follows:
    Module CleaningOrder
    
        Const UnitPriceShirts As Double = 1.25
        Const UnitPricePants As Double = 1.95
        Const UnitPriceOtherItems As Double = 3.25
        Const TaxRate As Double = 5.75
    
        Sub Main()
    
            Dim CustomerName As String, CustomerPhone As String
            
    	. . . No Change
    
        End Sub
    
    End Module
  2. To execute the program, press F5
  3. Enter values as follows:
     
    Customer Name: Shawn Nitty
    Customer Phone: (301) 423-7744
    Order Date: 04/11/2008
    Order Time 09:12
    Number of Shirts: 0
    Number of Pants: 2
    Number of Other Items: 0
  4. Enter the amount tended as 20
  5. Close the message box and 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:

  • Right-click the name of the module and click Open
  • Double-click the module

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:

  • In the top section of the Code Editor, click its label (or tab)
  • On the main menu, click Window and click the name of the file

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

  • Right-click the name of the module and click Rename. Type the desired name with the .vb extension and press Enter
  • Click the name of the module. In the Properties window, edit the entry in the File Name field

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"
        MsgBox("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
        MsgBox(Information)
    End Sub

End Module

This would produce:

Private

Practical LearningPractical Learning: Declaring Global Private Variables

  1. Change the document as follows:
    Module CleaningOrder
    
        Const UnitPriceShirts As Double = 1.25
        Const UnitPricePants As Double = 1.95
        Const UnitPriceOtherItems As Double = 3.25
        Const 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
        MsgBox(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
  • If a module is set to Friend, its Public and Friend members can be accessed by other members of modules of the same application. The public members cannot be accessed outside of the same application. This means that if you create an application A that has a friend module M and that module contains a public variable V, that variable V cannot be accessed by a module N from another application B
  • If a module is set Public:
    • Its Friend members can be accessed by friend and public modules of the same application. The friend members cannot be accessed outside of its application (even if the module is Public)
    • Its Public members can be accessed by modules inside the same application and modules in other applications (outside its application)

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:

  • You can write the names of both variables on the same line, separated by a comma, and ending the line with the common data type:
     
    Module Exercise
        Sub Main()
            Dim NumberOfPages, Category As Integer
            Dim MagazinePrice As Double
        End Sub
    End Module

    In this case, both variables NumberOfPages and Category, are the same type, Integer

  • You can also declare, on the same line, variables that use different data types. To do this, type the Dim keyword followed by the variable name and its data type with the As keyword. Then type a comma, followed by the other variable(s) and data type(s). Here is an example
     
    Module Exercise
        Sub Main()
            Dim NumberOfPages, Category As Integer
            Dim CountryName As String, MagazinePrice As Double
        End Sub
    End Module

    In this case, CountryName is a string variable while MagazinePrice is a Double variable

You can use the same techniques when declaring many global variables. Here are examples:

Module Exercise
    Friend FirstName As String, LastName As String
    Private DateHired As Date, HourlySalary As Double

    Sub Main()
        
    End Sub

End Module

After declaring the variables, you can initialize and use them as you see fit.

Read-Only Variables

We have indicated that when a variable is declared, it receives a default initialization unless you decide to specify its value. Whether such a variable has been initialized or not, at any time, you can change its value by reassigning it a new one. Here is an example:

Module Exercise

    Sub Main()
        ' Initializing a variable when declaring it
        Dim Number As Double = 155.82
        MsgBox("Number: " & Number)

        ' Changing the value of a variable after using it
        Number = 46008.39
        MsgBox("Number: " & Number)
    End Sub

End Module

This would produce:

Number

Number

In the same way, we saw that you could declare a variable at module scope outside of Main and then initialize or change its value when necessary. Here is an example:

Module Exercise

    Private UnitPrice As Double
    Private DateOfBirth As Date = #12/5/1974#
    Private Number As Double

    Sub Main()
        ' Initializing a variable
        Number = 155.82
        MsgBox("Number: " & Number)

        ' Changing the value of a variable after using it
        Number = 46008.39
        MsgBox("Number: " & Number)
    End Sub

End Module

When declaring a variable, as the programmer, you should have an idea of how you want to use the variable and what type of values the variable should hold. In some cases, you may want the variable to hold a constant value and not be able to change it. We saw earlier that such a variable could be declared as a constant. An alternative is to declare it with the ReadOnly keyword. While a constant variable can be declared locally, a ReadOnly variable cannot. It must be declared globally.

As done for a constant, when declaring a ReadOnly variable, you should initialize it. If you do not, the compiler would assign the default value based on its type. For example, a number-based variable would be initialized with 0 and a String variable would be initialized with an empty string. As done so far, to initialize the variable, use the assignment operator followed by the desired value.

Like a constant, after declaring and optionally initializing a ReadOnly variable, you cannot change its value. Based on this, the following code would produce an error:

Module Exercise

    Dim UnitPrice As Double
    Dim DateOfBirth As Date = #12/5/1974#
    ReadOnly Number As Double = 155.82

    Sub Main()
        ' Initializing a variable
        Number = 155.82
        MsgBox("Number: " & Number)

        ' Changing the value of a variable after using it
        Number = 46008.39 ' Error: You cannot assign a value to
        '                   a ReadOnly variable after initializing it
        MsgBox("Number: " & Number)
    End Sub

End Module

In the Microsoft Visual Basic 2010, the parser would signal the errors by underlining the read-only variable when you try changing its value. A window named Error List would also point out the problems:

In the Microsoft Visual Basic 2008, the parser would signal the errors

This means that a ReadOnly variable must be assigned a value once, when initializing it.

Managing Variables

 

Accessing a Variable

As mentioned already, you will write your code in normal text editors, whether using Notepad, the Code Editor of Microsoft Visual Studio, or else. Also, you may be familiar already with how to look for a character, a symbol, a word, or a group of words in a document. Just as reminder, on the main menu of the application, you can click Edit -> Find... This would display a dialog box where you can type the item and click Find. If you are using Microsoft Visual Studio and if you want to find different occurrences of a known character, symbol, word, or group of words, first select that item. Then:

  • On the main menu, click Edit -> Quick Find
  • Press Ctrl + F

In the same way, if you have a variable that is used more than once in your code and you want to see all places where that variable is used, simply click the name (and wait two seconds) and all of its occurrences would be highlighted:

Name Selection

To get a list of all sections where the variable is used, if you are using Microsoft Visual Studio:

  • In the Code Editor, right-click the name of the variable and click Find All References

Find All References

  • Press Ctrl + F12

This would produce a list of all sections where the variable is used and would display the list in the  Find Symbol Results window:

Find All References

To access a particular section where the variable is used, double-click its entry in the list int the Find Symbol Results window.

Cutting, Copying, and Pasting Code

Normally, from your knowledge of using computers, you probably already know how to select, cut, and copy text. These two operations can be valuable to save code in Microsoft Visual Studio. This means that, if you have code you want to use in different sections, you can preserve it somewhere to access it whenever necessary.

To save code to use over and over again, first type the code in any text editor, whether in Notepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code from any document where text can be copied, including a web page. Select that code and copy it to the clipboard. To preserve it, in Microsoft Visual Studio, display the Toolbox (on the main menu, you can click View -> Toolbox). Right-click an empty area on the Toolbox and click Paste:

Toolbox

An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag it and drop it on the Toolbox. In the same way, you can add different code items to the Toolbox. After pasting or adding the code to the Toolbox, it becomes available. To use that code, drag it from the Toolbox and drop it in the section of the Code Editor where you want to use it.

Renaming a Variable

As we will see throughout our lessons, there are many names you will use in your programs. After creating a name, in some cases you will have to change it. You can find where the name is and edit it. If the name is used in many places, you can continue looking for it and modify it. There is a chance you will make a mistake. If you are writing your code using a text editor, you can use the Edit -> Replace option of the main menu to find and replace every instance of that name. You can use the same approach in the Code Editor. Unfortunately, this technique works for only one file. If your project has many files and the name is used in those files, it would be cumbersome to remember to change the name in all of them.

Microsoft Visual Studio makes it easy to find and change a name wherever it is used. Consider the following code:

Module Exercise
    Public Sub Main()
        Dim nbr As Integer

        nbr = 148

        System.Console.WriteLine(nbr)
    End Sub
End Module

To change the name of a variable, in the Code Editor, double-click the name of the variable and edit (change) it. The name will then have a small underline:

Rename

If you position your mouse on it, a tag would appear and you can click the arrow to reveal a short menu:

Rename

If you click the Rename option, all instances of the variable would be changed.

Accessing a Variable's Declaration

If you create a long document that has many lines of code, in a certain section you may encounter a variable but you want to find out where it was declared. If you are using Microsoft Visual Studio, to access the place where a variable was declared:

  • Right-click the variable and click Go To Definition...

Go To Definition

  • Click the name of the variable and press Shift + F2

In both cases, the caret would jump to where the variable was declared.

Accessing a Line of Code by its Index

If you are using the Code Editor of Microsoft Visual Studio, if you create a long document that has many lines of code, if you want to jump to a certain line of code:

  • On the main menu, click Edit -> Go To...
  • Press Ctrl + G

This would display a dialog box. Enter the line number and click OK or press Enter.

ApplicationApplication: Ending the Lesson

  1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> Close Project (Microsoft Visual Basic 2010 Express)
  2. When asked whether you want to save, click Discard
 
 

Previous Copyright © 2008-2016, FunctionX, Inc. Home