In this hour, we will cover
What a programming language is
What variables are and how to declare them
How to assign values to variables
What data types are and why they are important
Visual Basic’s operators and how to use them
Typing rules
As discussed earlier, ASP.NET web pages are composed of two portions: an HTML portion, which contains HTML and Web controls; and a source code portion, which contains the ASP.NET web page’s server-side code. You can write the source code for an ASP.NET page in one of two programming languages: Visual Basic or Visual C# (often referred to as just C#).
Most beginning developers find Visual Basic a much easier language to learn than C#, mainly because Visual Basic’s syntax and structure are much closer to everyday English than C#’s. Therefore, all the source code portions of ASP.NET web pages discussed throughout this book use Visual Basic as the programming language.
If you are new to programming, you likely found the source code portions of the examples in Hours 2 and 4 to be a bit daunting. Don’t worry; in this hour and the next two, we’ll take an in-depth look at Visual Basic. By the end of these three hours, you’ll be able not only to make sense of code similar to that in previous hours, but also to write it on your own.
The contents of this hour and the next two are geared toward readers who have had little to no programming experience. If you are already fluent with the Visual Basic programming language, feel free to skip ahead to Hour 8, “ASP.NET Web Controls for Displaying Text.”
When computers were first designed in the early twentieth century, they were created to carry out mathematical computations that, at the time, were performed by humans. Computers were preferred over humans because they could perform the calculations faster, could work around the clock, and were not susceptible to error. For example, a computer doesn’t forget to carry the one when adding two numbers, an error every human has likely made at some point.
Computers then, as computers today, were built to accept a sequence of instructions and to carry out these instructions in the order in which they arrived. This made computers ideal for solving problems that could be broken down into a sequence of simple steps. For example, addition of large numbers can be broken down into simpler addition problems by first adding the numbers in the ones place, then the tens place, and so on, carrying over a digit into the preceding column if needed.
For a computer to solve a problem, though, it first needs to be told the precise sequence of steps to perform. Think of a computer as a very obedient young child, one who can understand only simple words and commands and will always do exactly as you instruct. For instance, if you want this child to go to sleep, you would have to tell him first to go to his bedroom, which might require that you first tell him to start walking toward the stairs. Then you would need to give instructions to step up the first step, then the second, and so on. After that, you might need to tell him to walk down the hall to his room. You would then need to tell him to open his door, to walk into his room, to lie down in bed, and finally, to fall asleep.
The verbal commands you give the child must be simple ones the child can understand. That is, if you said, “My beloved nipper, I fervently implore you to acquiesce to slumber,” the child would wonder what in the world you were saying. Similarly, when you’re providing instructions to a computer, the instructions must conform to a specific syntax and structure.
Specifically, computers understand commands only from particular programming languages. A programming language is a language with a well-defined syntax and semantics.
Multitudes of programming languages exist. When creating ASP.NET web pages, however, we are restricted to using .NET-compatible programming languages, such as Visual Basic and C#.
Many .NET-compatible programming languages exist, such as JScript.NET, COBOL.NET, Visual C++, and others. However, ASP.NET web pages are most typically created with either Visual Basic or C#. In fact, Visual Web Developer supports using only these two languages.
Although many different programming languages exist, all share some common features, including the following:
A means to store data temporarily—. In Visual Basic, variables
are used to store data. We’ll be discussing variables in the next section, “Declaring and Using Variables.”
A set of operators that can be applied to the data stored in variables—. One such operator is +
, which sums the values of two variables. We’ll look at the operators available in Visual Basic in the “Examining Visual Basic Operators” section.
A variety of control structures that can be used to alter the flow of instructions based on the value of variables—. The control structures in Visual Basic are covered in Hour 6, “Managing Program Flow with Visual Basic’s Control Structures.”
A way to modularize source code into reusable units—. In Visual Basic, code can be compartmentalized into subroutines and functions, as we’ll see in the next hour.
In this hour we look at Visual Basic’s syntax and semantics for storing and performing operations on data.
A variable is a location in the computer’s memory where you can temporarily store information, such as a number or a string.
In a programming language, a string is a sequence of characters and is delimited by quotation marks. An example of a string is
"Hello, world!"
Variables have three components to them:
A value, such as 5, or “Hello, world!”
A name, which is used to refer to the value of the variable.
A type, which indicates what types of values can be stored. For example, a variable of type Integer
can store values like 5 and –858. A variable of type String
can store values like “Hello, world!” and “Jisun is a toad.”
Because a variable’s type dictates what data can be stored in the variable, a variable’s type commonly is referred to as its data type.
Think of a variable as a box that can hold things only of a certain type. Each box has a name that you can use to reference the contents in a particular box. Figure 5.1 shows a box named Age
that can accept integer values. We can place values like 29, 97, –3, 829, 294, and 1,334,128, into Age
. In Figure 5.1, we’ve placed the value 29 into Age
.
The name and data type of a variable are immutable. That is, after the variable’s name and type have been specified, they cannot change during the program’s execution. The variable’s value, on the other hand, is mutable, meaning that it can change over the course of the program’s execution.
Variables alter their value through assignment statements. An assignment statement assigns a value to a variable using the =
operator and has the following form:
variableName = value
This statement assigns value
to the value of the variable variableName
.
The =
operator is often referred to as the assignment operator. We will discuss this operation in more detail in the “Visual Basic’s Assignment Operators” section.
To use a variable, you must first declare the variable using the Visual Basic Dim
statement. When declaring a variable, you must provide both the name and data type of the variable; you may optionally specify the value. For example, to create a variable named Age
that accepts values of type Integer
, you would use the following Dim
statement:
Dim age as Integer
More generally, the Dim
statement has the following form:
Dim variableName as type
We’ll examine the Dim
statement in much greater detail in the “Examining the Dim
Statement” section. First, though, we need to look at the rules for naming variables, as well as the available variable types.
Each programming language imposes its own set of rules for naming variables. Variable names in Visual Basic can start with an alphabetic character or an underscore character and be followed by zero to many underscores, alphabetic characters, or numeric characters.
Variable names in Visual Basic may be anywhere from one character long to 16,383 characters long. They are not case sensitive, meaning that upper- or lowercase does not matter. Therefore, the variable name Age
is equivalent to the variable names AGE
, age
, and aGe
.
Some examples of valid variable names are
Age
message2
_xyz123abc
txtPassword
If a variable name begins with an underscore, it must be followed by at least one other character. That is, you cannot have a variable simply named _
.
Some examples of invalid variable names are
3Age
—Invalid because a variable name cannot start with a numeric character.
_
—Invalid because if a variable name begins with an underscore, it must be followed by at least one other character.
234
—Invalid because a variable name cannot start with a numeric character.
When you’re naming your variables, it is important to choose names that make sense given the information the variable will store. For example, if you are going to use a variable to store the product of two numbers, you might want to name that variable Product
, or some other descriptive name, rather than using something ambiguous, like x
or variable3
.
Recall that the data type of a variable dictates what type of value can be stored in the variable. For example, a variable of type Integer
can store only values that are integers (negative and positive whole numbers).
If you have worked with ASP, ASP.NET’s predecessor, you’ve likely had experience with VBScript, a watered-down version of Visual Basic 6.0, which was the version of Visual Basic that predated Microsoft’s .NET platform. With VBScript, variables were loosely typed.
Loosely typed variables are variables that are declared without an explicit data type. Their type is inferred by their assigned value. In VBScript you could write code that looked like so:
1: Dim x 2: x = "Hello, World!" 3: x = 4
Note that the Dim
statement on line 1 does not contain a type (that is, it does not read: Dim x as String
). The type of x
is dynamically inferred by the value assigned to it. Therefore, on line 2, when x
is assigned the value “Hello, World!”, which is a string, x
’s type is considered to be of type String
. On line 3, however, x
is assigned the value 4, which is an integer. After line 3, x
’s type now is considered to be of type Integer
.
The opposite of loosely typed is strongly typed. In strongly typed programming languages, all variables must be declared to be of a certain type. After a variable has been declared to be a certain type, it can be assigned only values that correspond to that type.
With loosely typed languages, any value can be assigned to any variable, and the value being assigned determines the variable’s type. With strongly typed languages, a variable’s type is explicitly specified, and only values corresponding to the variable’s type may be assigned to the variable.
Visual Basic is a strongly typed language. Therefore, all variables must be given an explicit data type, and the set of values that can be assigned to a given variable is limited by the variable’s type.
Because each type has a predefined set of values that can be assigned, it is important to give your variable an appropriate data type. For example, in Hour 4, “Designing, Creating, and Testing ASP.NET Web Pages,” we looked at an ASP.NET web page that calculated the monthly cost of a home loan. The variables used to hold the intermediary computations were of type Decimal
, which is a numeric type that stores numbers with decimal places. Had we chosen to use variables of type Integer
, the calculation would have come out incorrectly. Consider the interest rate involved in the calculation, which might be 0.065 (for a 6.5% interest rate). Such a number cannot be expressed as an integer. Rather, we would have to use 0 or 1 (or some other whole number), which would clearly produce an incorrect answer. For this reason, using the correct type is important.
Let’s take a look at some of the most commonly used data types in Visual Basic.
Integers are whole numbers that can be either positive or negative. For example, 34, 76, –3,432, and 234,124 are all valid integers, whereas 12.4 and –3.14159 are not.
There are three types of integer data types, each differing in the range of numbers it can hold. The most common integer type is type Integer
, which can accept values ranging from –2,147,483,648 to 2,147,483,647. To create a variable of type Integer
, use the following syntax:
Dim variableName as Integer
If you need to store larger or smaller integer values, you can use the Long
data type, which accepts integer values ranging from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. To create a variable of type Long
, use the following syntax:
Dim variableName as Long
If you need to store much smaller integer values, you can use the Short
data type, which can store integers ranging from –32,768 to 32,767. To create a variable of type Short
, use
Dim variableName as Short
Integer
variables cannot store numbers that have decimals. If you perform an operation that results in a number with decimal places and then assign this number to an Integer
variable, the decimals will be truncated. If you need to work with variables that support decimal places, you must use one of Visual Basic’s three nonintegral numeric data types.
The first nonintegral numeric data type is Single
, which can accept values ranging from –3.4028235E+38 through –1.401298E–45 for negative values and from 1.401298E–45 through 3.4028235E+38 for positive values.
In scientific notation, the number following the E represents the number’s magnitude. The magnitude specifies the number of decimal places in the number. For example, 6.45E+8 is equal to 6.45 * 10^8, or 645,000,000, and 6.45E–8 is equal to 6.45 * 10^–8, or 0.0000000645. Therefore, 3.4028235E+38 is a very, very big number!
To create a variable of type Single, use the following syntax:
Dim variableName as Single
A more precise nonintegral numeric data type that also allows for larger numbers is Double
, which can accept values ranging from –1.79769313486231570E+308 through –4.94065645841246544E–324 for negative values and from 4.94065645841246544E–324 through 1.79769313486231570E+308 for positive values. To create a variable of type Double
, use the following syntax:
Dim variableName as Double
The third and final nonintegral numeric data type is Decimal
, which scales the decimal place by powers of 10. Decimals can have from 0 to 28 decimal places. With zero decimal places, the largest number a Decimal can have is 79,228,162,514,264,337,593,543,950,335 (the smallest being –79,228,162,514,264,337,593,543,950,335). The Decimal can have, at most, 28 decimal digits. Hence, the largest number with 28 decimal digits is 7.9228162514264337593543950335. To create a variable of type Decimal
, use the following syntax:
Dim variableName as Decimal
A Boolean variable is a variable that can be assigned only one of two values: True
or False
. To create a Boolean variable, use the Boolean
variable type. The following syntax demonstrates how to create a variable of type Boolean
:
Dim variableName as Boolean
A string is a sequence of characters. For example, “ASP.NET is fun!” is a string composed of 15 characters, the first being A
, the second being S
, and so on, with the 15th one being !
. To create a variable that can store string values, use the type String
. To create a variable of type String
, use the following syntax:
Dim variableName as String
To create a variable that stores dates, set the variable’s data type to DateTime
using the following syntax:
Dim variableName as DateTime
A DateTime
variable can store dates between midnight on January 1, 0001, through 11:59:59 p.m. on December 31, 9999.
Visual Basic contains a catchall type, a data type that can be assigned any value. This base type is the Object
type. The Object
type is, by its nature, extremely flexible because you can assign a variable of any type to it. For example, as the following code shows, you can assign a string to a variable of type Object
, and then an integer, and then a nonintegral number:
Dim catchall as Object catchall = "Jisun" catchall = 4 catchall = 3.14159
Despite its flexibility, you should rarely, if ever, create a variable of type Object
. The benefit of using more specific types like Integer
, String
, and Decimal
is that if you accidentally try to assign an inappropriate value to one of these variables, Visual Web Developer displays an error message.
As we discussed earlier, you must declare a variable before you can use it. In declaring a variable in a strongly typed programming language, you must provide its name and data type. In Visual Basic, this is accomplished using the Dim
statement.
In its simplest form, the Dim
statement specifies the variable’s name and type:
Dim variableName as type
To declare three variables of type Integer
, you can use three separate Dim
statements, such as:
Dim a as Integer Dim b as Integer Dim c as Integer
Or you can use one Dim
statement, separating each variable name and type with a comma, such as
Dim a as Integer, b as Integer, c as Integer
You can also supply a comma-delimited list of variable names and just one type. In this instance, all the variable names appearing before the data type will share the same type. That is, you can declare three variables, a
, b
, and c
, all to be of type Integer
using the following syntax:
Dim a, b, c as Integer
Using the syntax you’ve seen to this point, if you wanted to create a variable named a
of type Integer
and have it assigned the value 6, you’d write code like:
Dim a as Integer a = 6
The preceding syntax is fine as is, but you can save yourself a line of code by combining the assignment and variable declaration. To do this, use the following syntax:
Dim a as Integer = 6
Dim variableName as type = value
I find that merging a variable’s declaration and assignment on the same line of code, if possible, results in more concise and readable code.
In mathematics there are numbers and operators. Numbers are values like 4, 17.5, and pi, whereas operators are actions performed on the numbers, like negate, add, subtract, multiply, and divide. Numbers, by themselves, aren’t very interesting. But after you start applying operators to numbers, you can do all sorts of things, from balancing your checkbook to calculating the thrust needed to launch a satellite into orbit.
Visual Basic has variables and operators. Variables are like the numbers in mathematics. Visual Basic’s operators—like those in mathematics—perform actions on variables. Many of the traditional mathematical operators are found in Visual Basic. For example, to add two numeric variables in Visual Basic, you use the +
operator. To multiply two numeric variables, you use the *
operator.
Different classes of operators exist, the most important being arithmetic operators, comparison operators, the concatenation operator, and assignment operators. We’ll examine these four classes of operators in the following four sections.
The four most frequently used arithmetic operators in Visual Basic are +
, –
, *
, and /
, which perform addition, subtraction, multiplication, and division, respectively. These operators are referred to as binary operators because they operate on two variables.
For example, the following code adds the Integer
variables b
and c
and assigns the sum to a
:
Dim a, b, c as Integer b = 15 c = 20 a = b + c
The –
operator can be used both as a binary operator and as a unary operator. A unary operator is an operator that operates on just one variable. When the –
operator is used as a unary operator, it performs the negation of a number. Consider the following code:
Dim a, b, c as Integer b = 15 c = 20 a = –(b + c)
Here, a
would be assigned the value –35. The -
operator is used as a unary operator on the expression b + c
, thereby negating the value returned by b + c
.
Note that parentheses can be used to determine the order of operations. If, in the preceding code snippet, instead of
a = –(b + c)
we had used
a = –b + c
a
would have been assigned the value 5 because negation has precedence over addition. That is, when the expression -b + c
is evaluated, b
is negated first, and then its negated value is added to c
. With -(b + c)
, first b
and c
are summed, and then the resulting sum is negated.
The arithmetic precedence rules in Visual Basic mirror the standard precedence rules of mathematics. If you ever need to alter the order of operations, use parentheses to group those expressions that should be evaluated first.
The /
operator always returns a nonintegral numeric value, even if the resulting quotient does not have a remainder. That is, the value returned by 4 / 2
is the nonintegral numeric value 2.0, not the integer value 2. Of course the /
operator can also have a quotient with a decimal remainder; for example, the value returned by 3 / 4
is 0.75.
Comparison operators are binary operators that compare the value of two variables. The six comparison operators are listed in Table 5.1. Comparison operators always return a Boolean value—True
or False
—depending on the operator and the value of the two variables being compared.
The following statements evaluate to True
:
4 < 8 3.14159 >= 2 "Bob" <> "Sue" (10/2) = (20/4) 4 <= 4
The following statements evaluate to False
:
7 > 100 "Bob" = "Frank" (10/2) = 7.5 4 < 4
Comparison operators are commonly used in control structures. We explore control structures in detail in Hour 6.
The concatenation operator concatenates two string variables. Concatenating two strings produces a string that consists of the contents of the second string appended to the contents of the first. The string concatenation operator in Visual Basic is the ampersand, &
.
Let’s look at a quick code snippet to see how the concatenation operator works. Consider the following code:
Dim FirstWord as String = "ASP.NET" Dim SecondWord as String = "is" Dim ThirdWord as String = "neat" Dim Sentence as String Sentence = FirstWord & " " & SecondWord & " " & ThirdWord & "."
The variable Sentence
will end up with the value “ASP.NET is neat.” The first three string variables—FirstWord
, SecondWord
, and ThirdWord
—are each declared and assigned the value. Next, the string variable Sentence
is declared and is assigned the value of each of the three words concatenated together, with a space between each word and a period at the end.
To accomplish this, we use the &
operator to join together six strings. First, the string FirstWord
and “ ” are concatenated, resulting in the temporary string “ASP.NET “. I use the word temporary here because this string is immediately concatenated with SecondWord
, resulting in “ASP.NET is”, which is then concatenated with “ ”, resulting in “ASP.NET is”. Next, this is concatenated with ThirdWord
, giving “ASP.NET is neat”, and finally this is concatenated with “.”, resulting in “ASP.NET is neat.”, which is then assigned to the variable Sentence
.
In many situations, we may want to insert the value of a string variable into another string. For example, imagine that we have a variable called UserFirstName
that contains the user’s first name, and we want to display a message on the web page that reads “Hello, FirstName”, where FirstName is the value of the variable UserFirstName
. That is, if the value of UserFirstName
is “Scott”, we want the message “Hello, Scott” to appear.
To accomplish this, we would use code like
Dim Output as String Output = "Hello, " & UserFirstName
It is important to realize that after these two lines of code execute, the variable Output
will contain the value “Hello, FirstName”, where FirstName is the value of UserFirstName
. Note that we did not use
Dim output as String output = "Hello, UserFirstName"
Had we used this syntax, the value of Output
would be precisely as we indicated: “Hello, UserFirstName”. To insert the value of UserFirstName
into the string Output
, we need to concatenate the string “Hello,” with the value of UserFirstName
. This is done using the concatenation operator, not by simply typing the variable name into the string.
The most common assignment operator is the =
operator, which takes the form
variableName = value
For example, to assign the value 5 to an integer variable, we can use the following code:
Dim Age as Integer Age = 5
The value assigned to a variable can be things more complex than simple values like 5. The value can be an expression involving other operators. For example, we might want to add two numbers and store their sum in a variable. To accomplish this, we could use code like
'Create three integer variables Dim sum, number1, number2 as Integer number1 = 15 number2 = 20 'Assign the sum of number1 and number2 to sum sum = number1 + number2
In many situations we need to routinely update a variable’s value in some fashion. One of the most common applications of this is in a loop, where we increment (or decrement) the value of a variable by a certain amount in each iteration. We’ll see some concrete examples of loops in the next hour.
We could use the following code to increment a variable by 1:
Dim SomeIntegerVariable as Integer = 0 ... SomeIntegerVariable = SomeIntegerVariable + 1 ...
Initially, SomeIntegerVariable
is declared with an initial value of 0. Sometime later we want to increment the SomeIntegerVariable
by 1. This involves adding 1 to the current value of SomeIntegerVariable
and then storing the new value back into SomeIntegerVariable
. If SomeIntegerVariable
equals 0, then
SomeIntegerVariable = SomeIntegerVariable + 1
will take the value of SomeIntegerVariable
(0), add 1 to it (yielding 1), and store 1 into SomeIntegerVariable
. The next time the line
SomeIntegerVariable = SomeIntegerVariable + 1
is encountered, SomeIntegerVariable
will equal 1. This line of code will first evaluate SomeIntegerVariable + 1
, which is the value of SomeIntegerVariable
(1) plus 1. It will then assign this value (2) back into SomeIntegerVariable
. As you can see, this line of code increments the value of SomeIntegerVariable
by 1 regardless of the current value of SomeIntegerVariable
.
Because incrementing the value of a variable is a common operation, Visual Basic provides an alternative assignment operator to reduce the amount of code we need to write. This shorthand operator, +=
, has the form
variableName += value
and has the effect of adding value
to the current value of variableName
and then storing the resulting value of this addition back into variableName
. The following two lines have the same meaning and produce the same results—they increment SomeIntegerVariable
by 1:
SomeIntegerVariable = SomeIntegerVariable + 1
and
SomeIntegerVariable += 1
In addition to +=
, a number of other shorthand assignment operators exist, as shown in Table 5.2. Along with the shorthand arithmetic operators, you’ll notice the shorthand concatenation operator, &=
. This and the +=
operator are the two shorthand assignment operators we’ll use most often.
Table 5.2. The Shorthand Assignment Operators
Operator | Description |
---|---|
|
|
|
|
|
|
|
|
|
|
Recall that Visual Basic is a strongly typed language. This implies that all variables declared in a Visual Basic program must be given an explicit data type. Furthermore, the set of values that can be assigned to a variable is limited by the variable’s type. That is, a variable that is of type Integer
can be assigned only positive or negative whole number values that range between, approximately, positive two billion and negative two billion.
What happens, though, when you try to assign a nonintegral number to an integer variable, or when you try to assign an integer to a nonintegral numeric variable? What about when you try to assign a string variable to a nonintegral numeric variable, or an integer variable to a string variable?
Because Visual Basic is strongly typed, a value of one type cannot be assigned to a variable of a different type, which means you should not be able to assign an integer value to a nonintegral numeric variable. However, the following code will work:
Dim NonintegralVariable as Single NonintegralVariable = 5
Why does the preceding code snippet not produce an error? After all, doesn’t it violate the typing rules of Visual Basic by assigning an integer value to a nonintegral numeric variable?
Such an assignment is legal because, behind the scenes, Visual Basic casts the integer value (5) into a nonintegral value (5.0) and then assigns it to the nonintegral numeric variable.
Casting is the process of changing the type of a variable or value from one type to another. There are two types of casting: implicit casting and explicit casting.
Implicit casting is casting that occurs without any needed intervention or instructions by the programmer. In the previous code snippet, implicit casting is utilized because the integer variable 5 is cast to a nonintegral representation of 5.0 without any extra code provided by us, the programmers.
The documentation accompanying the .NET Framework SDK refers to implicit casting as coercion.
Explicit casting, on the other hand, requires that we, the programmers, explicitly indicate that a cast from one type to another should occur. To explicitly cast a variable from one type to another, use Visual Basic’s built-in CType
function, which has the following syntax:
CType(variableName, typeToCastTo)
The CType
function casts the variable variableName
from its current type to the type specified by typeToCastTo
. The following code snippet explicitly casts a value of type Integer
to type Single
:
Dim NonintegralVariable as Single NonintegralVariable = CType(5, Single)
In addition to Visual Basic’s CType
function, a Convert
class in the .NET Framework contains functions of the form To
DataType
. In lieu of CType
, we could use the Convert
class’s ToSingle
function to explicitly cast a value of type Integer
to type Single
:
NonintegralVariable = Convert.ToSingle(5)
Visual Basic can be run in one of two modes: strict and nonstrict. In the strict mode, implicit casting is allowed only for widening casts. In a widening cast, the set of legal values for the initial data type is a subset of the set of legal values for the target data type. For example, a cast from an integer type to a nonintegral type is a widening cast because every possible integer value can be expressed as a nonintegral value.
Another example of a widening cast is casting a variable of type Integer
to a variable of type Long
. This is a widening cast because any legal value for an Integer
is included in the set of legal values for a Long
.
The opposite of a widening cast is a narrowing cast. Consider casting a nonintegral numeric type to an integer type. Variables of nonintegral types can hold values that can be accurately cast to integral types. The nonintegral value 5.0, for example, can be accurately cast to the integral value 5. But what about nonintegral values like 3.14? There is no integer value that can represent 3.14 precisely. When we’re casting 3.14 to an integer, the resulting integer value is 3; the remainder is dropped.
Considering that narrowing casts can result in a loss of data, should Visual Basic allow for implicit narrow casts, or would it be prudent for the language to require that an explicit cast be used if a narrowing cast is required?
Truly strongly typed programming languages would require that all narrowing casts be explicit. In this case, if you tried to use code that would invoke an implicit narrowing cast, an error would result. That is, in a truly strongly typed programming language, the following code would produce an error:
Dim Quotient as Integer Quotient = 8 / 4
The reason this would result in an error is that the /
operator returns a nonintegral number (2.0), which must be cast to an integer to assign it to Quotient
. However, this cast is a narrowing cast. In a truly strongly typed language, you would have to provide an implicit cast, like so:
Dim Quotient as Integer Quotient = CType(8 / 4, Integer)
or
Dim Quotient as Integer Quotient = Convert.ToInteger(8 / 4)
Older versions of Visual Basic allowed for implicit narrowing casts, however. Consequently, if Visual Basic implemented the rules inherent to truly strong typed programming languages, old Visual Basic code could not be reused as is in programs created with today’s version of Visual Basic; rather, the programmer would have to alter the code to include explicit casting.
The designers of Visual Basic decided to take a middle-of-the-road approach. By default, implicit narrowing casts are permitted, meaning that the code
Dim x as Integer x = 8 / 4
will run without error, assigning the integer value 2 to the variable x
.
Keep in mind that casting a nonintegral number to an integer drops the remainder portion of the nonintegral number. That is, after the following code is executed, the value of Quotient
will be 0:
Dim Quotient as Integer Quotient = 3 / 4
To disallow implicit narrow casting in an ASP.NET page’s source code portion, open the page’s source code file and add Option Strict On
at the top. With this option turned on, Visual Basic reports any implicit narrowing casts as errors in Visual Web Developer.
Listing 5.1 shows the contents of an ASP.NET page’s source code file with Option Strict On
(line 1). Because of this setting, Visual Web Developer reports that the implicit narrowing cast in the Page_Load
event handler is an error (see Figure 5.2).
Example 5.1. Implicit Narrowing Casts Are Disallowed Because of the Option Strict On
Setting
1: Option Strict On 2: 3: Partial Class _Default 4: Inherits System.Web.UI.Page 5: 6: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 7: Dim Quotient As Integer 8: Quotient = 8 / 4 'An implicit narrowing cast! 9: End Sub 10: End Class
In this hour we examined the syntax and semantics for variables and operators in Visual Basic. Variables are defined by three properties: their name, their data type, and their value. The name and data type of a variable are specified when the variable is declared and are immutable. Variables are declared in Visual Basic via the Dim
statement in the following fashion:
Dim variableName as type
The type of a variable dictates what values the variable can contain. Each type has a set of legal values. For example, a variable of type Integer
can store negative or positive whole numbers that range from –2,147,483,648 to 2,147,483,647.
A variable is assigned a value via an assignment statement, which is =
in Visual Basic. Along with the assignment operator, there are a number of other operators in Visual Basic, including arithmetic operators, like +
, -
, *
, and /
; comparison operators, like <
, <=
, >
, >=
, =
, and <>
; and the string concatenation operator, &
.
When you’re assigning a value to a variable, it is vital that the type of the value matches the type of the variable. If the types do not match, Visual Basic may be able to implicitly cast the value’s type into the needed type.
Casts can be implicit or explicit, narrowing or widening. An explicit cast can be declared by using Visual Basic’s built-in CType
function or by using the Convert
class’s methods. Visual Basic, by default, allows for implicit, narrowing casts. However, when you specify Option Strict On
in ASP.NET web page’s source code file, implicit narrowing casts are not allowed.
In the next hour we will look at control structures in Visual Basic. Control structures allow for changes in the program’s instruction execution. Commonly, this is translated into having specified portions of code executed repeatedly until some condition is met, or encapsulating a series of related instructions in a subroutine or function, which can then be invoked in a single line of code.
There are no exercises for this hour mainly because all that we know how to do in Visual Basic at this point is declare variables and assign values to these variables.
In the next hour we will look at Visual Basic control structures, which allows for code to be executed repeatedly or conditionally. After we have covered this material, you’ll be ready for some Visual Basic exercises.
18.225.55.151