Learn to program in Visual Basic .NET, the right way

The Basics - Variables

What are Variables?

A variable is an object that the programmer creates by specifying the: scope, name, data type, and optionally the value.

Most variables have dynamic values, this is to say that the value of the variable has the potential to change.

Syntax

The format for writing the code to declare variables, or in computer jargon the sntax for declaring variables, is as described in the following code block:

[modifier] [name] As [type]

This code example is not the actual code. Everything in the square brackets is a specific component that ultimately make up the variable.

Modifier

Modifiers determine at what scope a variable can be accessed at. In later lessons, modifiers will be described more in depth, but for now the Dim keyword will be used as the modifier in examples.

Name

The name is user defined, which means that the programmer gets to pick the variable name. A variables name must be unique and it follows the following naming rules:

  • Must start with a letter (upper or lower case) or an underscore.
  • The following characters may be alphanumeric (upper or lower case) or an underscore.
  • Names may only be one character long, however if the variable name starts with an underscore it must be proceeded with at least one alphanumeric character.
  • If the name is on the Keyword List, then it must be wrapped in square brackets.

The following demonstrates valid and invalid variable names:

'Valid
x
xyz
xyz123
x1y_
__var
[As]

'Invalid
1 'Cannot start with a number
_ 'Cannot be a single underscore
__ 'There was not preceeding alphanumeric characters
As 'Keyword was not wrapped in square brackets

Data Types

There are many different data types in Visual Basic .NET, all of which can be found here. Some of the more common data types are (in alphabetical order):

  • Boolean - True or False values.
  • Double - Numbers that can contain a decimal place.
  • Integer - Numbers that do not contain a decimal place.
  • String - Text values

Example

The following are some examples of how to declare a variable:

Fiddle: Live Demo

As mentioned above, variables can be declared with a value. Declaring variables with a value is known as intializing a variable.

The following are some examples of how to initialize a variable:

Fiddle: Live Demo

Remarks

Notice when initializing the String variable, that the value was wrapped in double quotation marks, this is how String values, aka - String literals, are represented.

I highly encourage that you visit the link provided earlier (and here again) to familiarize yourself with the various data types along with their respective literal(s).