Visual Basic 2005 Variables

A variable has a name and a value and stores values during program execution. In todays programming languages variables are not just names or placeholders for values. They also store and also possess a value.

Declaring Variables

To declare a variable use the Dim statement followed by the variables name, As keyword, and its type.

In a program, variables must be declared in advance. If the compiler is informed of all the variables and their types, it can produce the most compact and efficient code.

With VB .Net and 2005, variables should be declared by default. Microsoft VB compiler throws an exception if it comes across an undeclared variable.

When we declare a variable, we must also specify its type. One of the new terms in the VB 2005 documentation is "strictly typed", which means that a variable has a specific type and you cannot store a value of different type to the variable.

When we declare a variable we are actually telling the compiler the type of data we intend to store in each variable. This way the compiler can generate the code that handles the variables most efficiently. A variable that holds characters is different from a variable that holds numbers.

Variable initialization

We can also initialize variables in the same line that declares them. The following line declares an integer variable and initialize it to 35.

Dim minMarks As Integer 35

This statement is equal to the following two statements.

Dim minMarks As Integer
minMarks = 35

Types of variables

Visual Basic recognizes the following five categories of variables.

Numeric
String
Boolean
date
Object

The two major variable categories are numeric and string. Numeric variables store numbers, string variables stores text and Object variables store any type of data.


Numeric variables

All programming languages provide a variety of numeric data types, including the following:

Integers
Decimals
Single
Double




Decimal, Single and Double are the three basic data types for storing floating point numbers. The double type can represent these numbers more accurately than the single type and it is used almost exclusively in scientific calculations.

The Short data type is the same as the integer data type of vb6. The new Integer data type is the same as the long data type of VB6; The VB.Net Long data type is new and can represent extremely large integer values. The Decimal data type is new to VB.Net, and you use it when you want to control the accuracy of the calculations in terms of number of decimal digits.

Variables in VB 2005 are case insensitive. For example the variable names strName, strname, STRNAME all refer to the same variable in the code.

Scope is the section of the software program in which the variable is visible and can be manipulated. Along with a type, a variable also has a scope. When a variable is declared within a procedure, only that procedure has access to that variable. This is called a local variable because it the variable´s scope is limited to the particular procedure.

Following is the vb code for the Click event of a Button to calculate the sum of all numbers in the range 0 to 50.

Private Sub Buttonl_Click(ByVal sender As Object, - 
    ByVal e As System.EventArgs) Handles Buttonl.Click
	Dim i As Integer
	Dim Total As Integer
	For i = 0 to 50 Step 1 
		Total = Total + i
	Next
	MsgBox "The Total is" & Total 
End Sub

The variables 'i' and 'Total are local variables. If we are accessing the value of the 'Total' variable from another procedure, Visual Basic will return an error message that the variable is not declared.

The 'Total' variable is said to have procedure-level scope. It's visible within the procedure and invisible outside the procedure.

Another type of scope is the Block-Level scope. It is used in a If statement or while loop or for loop. A block level scope is visible only in a block of vb code.

If  total  < 100 Then 
   Dim i As Integer 
   i = sum + i 
End If

The i variable is not visible outside the block of the if..End If loop. If we attempt to use it before the If statement, or after the End If statement, VB will throw an exception.

Scope of a variable

Another type of scope is the module-level scope. Variables declared outside any procedure in a module are visible from within all procedures in the same module, but they're invisible outside the module. Setting variables from within many procedures can complicate the debugging of the software program. The following vb code demonstrates the module level scope.




Public Class class1  
	Shared x As Integer
	
	Shared Sub New()
          x=0  
	End Sub
End Class


The Lifetime of a Variable

The period which a variable holds a value is called the lifetime of a variable. This is in addition to to type and scope. Variables declared as Public exist for the lifetime of the software program. Local variables, declared within procedures with the Dim or Private statement, are alive as long as the procedure.

When the procedure ends, the local variables cease to exist and the allocated memory is returned to the system. When the same procedure is called again the local variables are recreated and initialized. If a procedure calls another procedure, its local variables retain their values while the called procedure is running. With the Static keyword we can force a local variable to preserve its value between procedures.

Using the function RunAvg(), we can keep a running value in memory. An example is shown below.

Function RunAvg(ByVal dblValue As Double) As Double
	RunTotal =RunTotal + dblValue
	NumofItems = NumofItems + 1
	RunAvg= RunTotal / NumofItems 
End Function

We must declare the variables RunTotal and NumofItems outside the function so that their values are preserved between calls. We can also declare them in the function with the Static keyword, as shown below.

Function RunAvg(ByVal dblValue As Double) As Double
	Static RunTotal As Double
	Static NumofItems As Integer
	RunTotal =RunTotal + dblValue
	NumofItems = NumofItems + 1
	RunAvg= RunTotal / NumofItems 
End Function

In VB6 we could declare all the variables in a procedure as static by prefixing the procedure definition with the keyword Static. This option is no longer available with the versions of VB.NET.

Note that variables declared in a module and outside a procedure take effect when the form is loaded and ceases to exist when the form is unloaded. If the form is loaded again, its variables are initialized, as if it is being loaded for the first time.

Variables are initialized when they are declared, according to their type. Numeric variables are initialized to zero, string variables are initialized to a blank string, and Object variables are initialized to nothing. If the variable is declared with an initializer (as in Dim i As Integer 50) it is initialized to the specified value.





cover image of azure cloud book

Develop Azure Applications

Azure Cloud is gaining popularity and is competing with Amazon Elastic Cloud and Google Cloud for a spot in the billion dollar Cloud computing space.

With this book learn how to use - Table (an Azure Table is different from a SQL Server Table), Queue, Blob storage services, use your local machine to create an Application and a Service, how Azure splits a Table to achieve Load Balancing, Scalability based on the Partition Key, AppFabric Service Bus, Access Control Service, role of Fabric Controller, features of Azure SQL Database and Content Delivery Network.

Many have mastered Cloud Programming and are enjoying the benefits. Why not you?

View Highlights » View Contents »
cover image of foundation database programming book

Create your Own Accounting Software

A foundation book to Master Accounting Software Development, VB.Net, C# and OOPs programming. Detailed explanation of the Accounting domain for programmers is included. SQL and ADO.Net is also covered in detail.

This book gives you a strong foundation in Application Development.

A thorough understanding of the contents will enable you to grasp the topics covered in the accompanying books quite easily. This is because, the accounting domain is dealt with great detail in this book.

The ideal book to get started with application development in the .Net world.

View Highlights » View Contents »

cover image of asp.net book

Create your Own WEB ERP Software using ASP.Net

This book opens you to the Web. Using ASP.Net, C# and SQL Server as the tools, you will learn to build a Multi Tier Web Application as recommended by Microsoft. You will learn implementing inline GridView control, Transaction Management for a layered Web Application, build Data Access component and a Business Layer component.

Opens you to a world of opportunities. You will be able to develop a Web ERP application including all the five modules and learn how to use the TreeView control and GridView control to implement transactions such as Purchase Invoice, Sales Order and Sales Invoice.

View Highlights » View Contents »
cover image of entity framework book

ASP.Net MVC 5 Application Development Using Entity Framework 6 and VS 2015

Entity frameworks is the latest buzz in .Net programming and is the data access technology for Microsoft OS based hand held devices and web applications. Learn to integrate EF into an ASP.Net Application and MVC application. Create, explore and query the Entity Data Model. Learn how to use ObjectDataSource control and GridView control in an ASP.Net Application.

Also, learn to build Three-Tier ASP.Net application, create a business-class, implement methods in the class to perform CRUD operations and bind a GridView to the ObjectDataSource control. Learn how to handle concurrency and managing Transactions.

View Contents »