3x + 5 = 20 x = 5where x is the variable.
In the context of a programming language, we can formally define a variable as an object with the following attributes:
access_type var_name As type [= inital_value]As mentioned above, variables must be assigned a name so they can be referenced or used. The name of a variable is what differentiates one variable from another. As mentioned, variables are assigned names in VB at the time they are declared. The naming rules for variables in VB are as follows:
In addition to the rules, there are also some typical conventions, or suggestions for variable naming:
Choosing a variable type is one of the more important decisions a programmer must make. The type a variable is assigned should be selected based upon the values the variable is expected to store. For example, if a variable is going to be used to store the outside temperature as a whole number, one might select Short or Integer. Note that selecting a Byte type for this would lead to problems, since a Byte type does not allow for negative values, if the temperature were to dip below zero. It is imperative when one selects the appropriate type when assigning data types to variables. Selecting an incorrect type can cause catastrophic problems when running a program; problems that are not only severe but difficult to diagnose.
Typically in VB, the access_type of a variable is specified using the keyword Dim (note the author does indeed recall where this term comes from). Assigning a variable name, type and access_type, we observe the following variable declaration statements:
Dim intAge As Integer Dim intSum As Integer Dim strFirstName As String Dim intAge, intSum As IntegerThe first declaration statement above declares a variable named intAge as an Integer type variable, as does the second line with the variable named intSum. The third line declares a String type variable named strFirstName. The final line declares two variables of type Integer. 3 It should be obvious from the names what each variable above will be used for. Observe how each of the variable names adhere to the rules and conventions listed above.
When declaring variables, if no initial value is assigned, VB initializes all variables to zero by default, or a value that closely resembles zero. Thus Integer types get a default value of 0, Double types get a default value of 0.0, and String types get a default value of Nothing. With respect to string types, it is important to note that Nothing, the empty string (""), and a string containing one space (" ") are very different objects. Nothing has no length, since it is not an existing object (it is a NULL reference). The empty string ("") is an object, with essentially nothing in it, thus has the length of zero. Finally, a string containing one space (" ") has a length of one.
In O-O speak, variable types are actually classes, where the declaration of a variable instantiates an object from that class. Thus declaring an Decimal variable, for example, is an instantiation of an Decimal object from the Decimal class. This object inherits all attributes from that class, such as the size of the variable (in bytes), range of possible values, etc. as described above. A pictorial representation of this follows:
1 The author is well aware that variable prefixing in .Net languages has
fallen out of favor. However, in the introductory classroom, I think variable prefixing is extremely useful; it helps
introductory students better understand variable typing, and make fewer mistakes with type mismatches.
2 Using the terms elemental (i.e. simple) and complex to describe data types
is somewhat misleading. It is true that a Char type is a simple type, and an Array is relatively complex. However,
one would certainly be correct that a Double is not as simple of a type. The point is that value types can be considered
as less complex that reference types in VB. Of course, the hole in this theory is the Structure definition,
which is a value type. See additional details about value and reference types at Microsoft's MSDN site
here.
3 This is perfectly legal VB syntax, however, it is not the preference of
the author. I favor one variable declaration per line. This helps eliminate erroneous type declarations as well as
provides space for comments on the remainder of the line. There are also initialization issues with multiple variables
per line with a single As statement.
I tend to use the prefix of con with constants, to remind myself I better not try to change it. An example of
declaring a constant might be the following:
Thus the value of the expression on the right of the equal sign (=) is assigned to the variable on the left.
The expression in the above can be a:
Some examples of valid variable assignment are as follows:
Constants
Const con_name As type = value
Some items of note when defining constants include:
Const conTaxRate As Double = 0.0625
Attempting to change the value of this constant elsewhere in the program will generate an
"Constant cannot be the target of an assignment" error.
Variable Assignment
var_name = expression
There are two issues to understand here of utmost importance:
intAge = 22
intSum = intSum + 10
strFirstName = "Mark" 'note the pair of quotation marks
intAnswer = intSum 'note both variables are the same type
strFirstName = Console.ReadLine() 'assignment from ReadLine method, which returns a String type
Below are some examples of invalid variable assignment. Make sure you understand the problem with each of the following:
intAge = abc 'value abc is not an Integer
intAge = "22" 'value 22 is not an Integer since enclosed in quotation marks
strName = 22 'value 22 is not a String type
intSum = 22.5 'value 22.5 is not a Integer type
strFirstName = Mark Thomas 'note the missing quotation marks
One important note here, even though the following statement is a valid algebraic statement:
22 = X
it is an erroneous statement in Visual Basic. This is because assignment always works right to left.
Variables and Arithmetic Operations
Operator Name | Symbol |  # Operands |
---|---|---|
addition | + | 2 |
subtraction | - | 2 |
multiplication | * | 2 |
division | / | 2 |
exponentiation | ^ | 2 |
negation | - | 1 |
Note that all operators above except the last require two operands. These are called binary operators. The last operator only takes one operand; this is called a unary operator. Note also that the negation operator uses the same symbol as subtraction. How does VB know whether the - operator is for subtraction or negation? The number of operands; if only 1, then it's negation, if 2 operands, it is subtraction. This is formally called operator overloading, and the operation performed is based upon the context of its usage. Operator overloading will be discussed in more detail later.
Looking at some examples of arithmetic using variables:
intSum = intSum * conTaxRate intSum = intSum / 100 intSum = intSum ^ 3
When considering typical types of arithmetic usage, two techniques emerge; counting and accumulation. Counting usually involves incrementing a variable (usually called a counter) by a single item or unit. This implies counting by 1, or sometimes by -1. A typical counter statement looks like:
intCount = intCount + 1Accumulation on the other hand, doesn't increment by a single value (like 1). Accumulation usually involves incrementing by some value, then adding that value to a variable, often called a sum. For example:
decSum = decSum + decItemPrice
? = (2 + 3) * (3 + 3) ' answer = 30 ? = 4 + 6 / 2 ' answer = 7 ? = 1 + 2 * 3 ' answer = 7 ? = -3 ^ 2 ' answer = -9To make precedence a bit more complex, if an expression contains operators of equal precedence, the order of operations is left to right. Thus:
? = 8 / 2 * 3 ' answer = 12 ? = 8 + 40 / 8 * 2 + 4 ' answer = 22 ? = 7 - 2 - 4 + 1 ' answer = 2The overriding rule of thumb here is when in dobut, use parentheses. See MSDN page on operator precedence for more details here.
There are two techniques for type conversion: 1) implicit and 2) explicit type conversion. Implicit type conversion takes place automatically by the VB compiler when no specific (explicit) conversion is employed. Explicit conversion must be implemented by the programmer using built in conversion methods to perform "correct" conversion. When using either technique of type conversion, one of two things will usually happen; you can try to convert a larger type (in memory size) to a smaller type, or you can try to convert a smaller type to a larger type. The former scenario is called narrowing, while the latter is called widening. Narrowing is similar to trying to put a large box inside of a smaller box, and as you can imagine, it does not work well. The same is true in VB.
With implicit type conversion, if you try to convert a larger type to a smaller type, an error will be generated. If you have Option Strict set to On (see below), you will get an "Option Strict On disallows implicit conversions from larger_type to smaller_type" error when narrowing occurs. As a rule of good programming, you should avoid any type of implicit conversion altogether.
When explicit data type conversion must be performed, VB provides numerous type conversion methods which allow for "valid" conversion. One of these classes of methods is the Convert1 class. The Convert class provides numerous methods for converting one base type to another base type, e.g. from an Integer to a Double. The general format is:
new_type_identifier = Convert.Tonew_type (old_type_expression)where new_type is the base class name of the new type. As an example, most data is entered as String data. If we wish to convert a String2 variable to an Integer type, we can use the Convert3 method as follows:
intValue = Convert.ToInt32 (strInput)As another example, to convert an Integer type variable to a Decimal type variable (make sure you understand that this is a widening conversion), we could use:
decValue = Convert.ToDecimal (intValue)It is important to note in the above example the data type on the left of the assignment operator, and the Convert.To type agree, as evident in the diagram below:
Whenever one is performing explicit type conversions, there are always issues to be aware of. For example, in the first example above (String to Integer), consider a user entering a string of "two". It should be obvious this cannot be converted to an Integer. Invalid input such as this will result in a serious run-time error being generated and program execution will halt. We will address how to handle these errors in a future section.
Another less obvious gotcha in type conversion is the following:
intValue = Convert.ToInt32 (decValue)Not only are Decimal types much larger than Integer types (i.e. narrowing will occur), there is no place to store the fractional component if it exists. Consider the following:
decValue = 3.14159 intValue = Convert.ToInt32 (decValue)Since we are using explicit conversion, no error will be generated here. However the resulting value stored in intValue will be 3, which may or may not be what was intended. It is imperative that one pays very close attention to matching like types on either side of the assignment operator, since these errors can be quite nasty and difficult to track down!
For more information regarding the Convert class members, look at Microsoft's MSDN site here.
Data Type | Type Character |
---|---|
Integer | I |
Short | S |
Long | L |
Single | F |
Double | R |
Decimal | D |
Char | C |
1 The Convert class belongs to the System namespace. Since the System
namespace is the top most hierarchical namespace, this namespace is imported by default so the System can be omitted.
2 When converting from a String type, there are class
methods that can be used other than the Convert class. You can also use the type.Parse methods.
Each of these .Parse methods belongs to the class of the base type. For example, see the Decimal.Parse method
here.
3 Do not let the .ToInt32 confuse you. An Integer type is actually a
32-bit signed integer type, which is the same type as Int32. There is no Convert.ToInteger method. This is
Microsoft's way of making this more complicated than it needs to be.
Assistance With Variable Assignment
Option Explicit On
Option Strict On
Do not hesitate to use both of these, they are your friends! The following examples show where data conversion can
go awry and Option Strict/Explicit will be of aid:
Option Explicit On Option Strict On 'program name: OptionOnExample Module OptionOnExample Sub Main() Dim intMyVar1 As Integer intMyVar1 = 10 intMyVar2 = 20 'error: intMyVar2 is not declared intMyVar1 = 1.2345678 'error: Option Strict On disallows 'implicit conversions End Sub End Module |
Option Explicit On Option Strict On 'program name: OptionOnExample2 Module OptionOnExample2 Sub Main() Dim dec1 As Decimal = 123.45D ' without the D, error Dim dec2 As Decimal Dim int1 As Integer int1 = dec1 ' Option Strict On disallows implicit ' conversions from Decimal to Integer int1 = Convert.ToInt32(dec1) ' int1 will equal 123 dec2 = int1 ' dec2 will equal 123.0D End Sub End Module |
Next Section: Console Programming | Table of Contents |
©2007, Mark A. Thomas. All Rights Reserved.