An operator is a symbol (e.g., =, +, >, &) that causes VB.NET to take an action. That action might be an assignment of a value to a variable, the addition of two values, a comparison of two values, concatenation of strings, etc.
In the previous sections, you've seen a number of operators at work. For example, the assignment operator (=) has been used to assign a value to a variable:
Dim myVariable As Integer myVariable = 15
In the code shown above, the value 15 is assigned to the Integer variable myVariable. In the section on branching you saw more sophisticated operators, such as the greater-than comparison operator (>) used to compare two values:
If valueOne > valueTwo Then
The preceding If statement compares valueOne with valueTwo; if the former is larger than the latter, the test evaluates true, and the If statement executes.
The following sections will consider many of the operators used in VB.NET in some detail.
VB.NET uses seven mathematical operators: five for standard calculations (+, -, *, /, and \), a sixth to return the remainder when dividing integers (Mod), and a seventh for exponential operations (^). The following sections consider the use of these operators.
VB.NET offers five operators for simple arithmetic: the addition (+), subtraction (-), and multiplication (*) operators work as you might expect. Adding two numbers returns their sum, subtracting returns their difference, and multiplying returns their product.
VB.NET offers two division operators: / and \. The forward slash or right-facing division operator (/) returns a floating-point answer. In other words, this operator allows for a fractional answer; there is no remainder. Thus, if you use this operator to divide 12 by 5 (12/5), the answer is 2.4. This answer is returned as a Double.
|
The backslash or left-facing division operator (\) performs integer division; that is, it returns an integer value and discards any remainder. Thus, if you use the integer division operator to divide 12 by 5 (12\5), the return value is truncated to the integer 2, with VB.NET discarding the remainder of 4. However, no cast is needed (even with Option Strict On) because you've explicitly asked for the integer value. Example 3-23 illustrates integer and fractional division.
Option Strict On Imports System Module Module1 Sub Main( ) Dim twelve As Integer = 12 Dim five As Integer = 5 Dim intAnswer As Integer Dim doubleAnswer As Double Console.WriteLine("{0} + {1} = {2}", _ twelve, five, twelve + five) Console.WriteLine("{0} - {1} = {2}", _ twelve, five, twelve - five) Console.WriteLine("{0} * {1} = {2}", _ twelve, five, twelve * five) ' integer division intAnswer = twelve \ five doubleAnswer = twelve \ five Console.WriteLine("{0} \ {1} = [integer] {2} [double] {3}", _ twelve, five, intAnswer, doubleAnswer) ' explicit cast required to assign to integer intAnswer = CInt(twelve / five) doubleAnswer = twelve / five Console.WriteLine("{0} / {1} = [integer] {2} [double] {3}", _ twelve, five, intAnswer, doubleAnswer) End Sub 'Main( ) End Module Output: 12 + 5 = 17 12 - 5 = 7 12 * 5 = 60 12 \ 5 = [integer] 2 [double] 2 12 / 5 = [integer] 2 [double] 2.4
In Example 3-23, you first declare two variables named twelve and five, which are initialized to contain the values 12 and 5, respectively:
Dim twelve As Integer = 12 Dim five As Integer = 5
You then pass the sum, difference, and product of twelve and five to the Console.WriteLine( ) method:
Console.WriteLine("{0} + {1} = {2}", _ twelve, five, twelve + five) Console.WriteLine("{0} - {1} = {2}", _ twelve, five, twelve - five) Console.WriteLine("{0} * {1} = {2}", _ twelve, five, twelve * five)
The results are just as you would expect:
12 + 5 = 17 12 - 5 = 7 12 * 5 = 60
The type of the variable to which you assign the answer affects the value that is ultimately saved. You cannot assign a floating-point answer to a variable of type Integer. So, even if you perform standard division and receive a fractional answer, if you assign that answer to an Integer variable, the result will be truncated�just as if you had used integer division (\) to begin with!
For example, you might create two local variables, intAnswer and doubleAnswer, to hold two quotients:
Dim intAnswer As Integer Dim doubleAnswer As Double
You then divide twelve by five twice. The first time you use integer division:
intAnswer = twelve \ five doubleAnswer = twelve \ five
The result returned by integer division, using the (\) operator, is always an integer. Thus, it does not matter whether you assign the result of integer division to a variable of type Integer or to a variable of type Double. This is reflected in the output:
12 \ 5 = [integer] 2 [double] 2
You then divide again, using the standard division operator (/), which allows for fractional answers:
intAnswer = CInt(twelve / five) doubleAnswer = twelve / five
The standard division operator returns a floating-point answer, which can be accommodated by a variable of type Double (as in your variable doubleAnswer). But assigning the result to an Integer variable (like intAnswer) casts the result to an Integer (and, because Option Strict is On, requires an explicit cast operator). The fractional portion is discarded, as shown in the output:
12 / 5 = [integer] 2 [double] 2.4
It is not uncommon to want to add a value to a variable and store the result back in the variable itself.
x = x + 5
While in mathematics the preceding line would make no sense, in Visual Basic .NET this is read "add 5 to x and store the results in x." Similarly, you might subtract 5 from x, and store the result in x:
x = x - 5
These statements are so common that, like many other languages, Visual Basic .NET implements a form of shorthand known as self-assignment. There are self-assignment variants of all the mathematical operators:
x += 5 ' x = x + 5 x -= 5 ' x = x - 5 x *= 5 ' x = x * 5 x /= 5 ' x = x / 5 x \= 5 ' x = x \ 5
You can also use self-assignment with strings:
Dim myString As String = "Hello " myString += "World"
After these two statements, myString contains the string "Hello World".
To find the remainder in integer division, use the modulus operator (Mod). For example, the statement 17 Mod 4 returns 1 (the remainder after integer division).
The modulus operator turns out to be more useful than you might at first imagine. When you perform modulus n on a number that is a multiple of n, the result is zero. Thus 80 Mod 10 = 0 because 80 is an even multiple of 10. This fact allows you to set up loops in which you take an action every nth time through the loop, by testing a counter to see if Modn is equal to zero, as illustrated in Example 3-24.
Option Strict On Imports System Module Module1 Sub Main( ) Dim counter As Integer ' count from 1 to 100 For counter = 1 To 100 ' display the value Console.Write("{0} ", counter) ' every tenth value, display a tab and the value If counter Mod 10 = 0 Then Console.WriteLine(vbTab & counter) End If Next counter End Sub ' Main End Module Output: 1 2 3 4 5 6 7 8 9 10 10 11 12 13 14 15 16 17 18 19 20 20 21 22 23 24 25 26 27 28 29 30 30 31 32 33 34 35 36 37 38 39 40 40 41 42 43 44 45 46 47 48 49 50 50 51 52 53 54 55 56 57 58 59 60 60 61 62 63 64 65 66 67 68 69 70 70 71 72 73 74 75 76 77 78 79 80 80 81 82 83 84 85 86 87 88 89 90 90 91 92 93 94 95 96 97 98 99 100 100
In Example 3-24, the value of the counter variable is incremented by 1 each time through the For loop. Within the loop, the value of counter modulus 10 (counter Mod 10) is compared with zero. When they are equal (counter modulus 10 is zero), the value of counter is evenly divisible by 10, and the value is printed in the righthand column.
|
The final arithmetic operator is the exponentiation operator (^), which raises a number to the power of the exponent. Example 3-25 raises the number 5 to a power of 4.
Option Strict On Imports System Module Module1 Sub Main( ) Dim value As Integer = 5 Dim power As Integer = 4 Console.WriteLine("{0} to the {1}th power is {2}", _ value, power, value ^ power) End Sub ' End of the Main( ) method definition End Module Output: 5 to the 4th power is 625
Visual Basic .NET offers two operators for concatenating strings: the concatenation operator (&) and the addition operator (+). Since the addition operator doubles as a concatenation operator, most VB.NET programmers prefer to use the concatenation operator (&) operator for concatenating, in order to avoid confusion with addition.
If you start with two strings, as in the following:
Dim s1 As String = "Hello " Dim s2 As String = "World"
you can concatenate the two strings together (append the second to the first) to create a new string (s3 in this case):
Dim s3 As String s3 = s1 & s2 Console.WriteLine(s3)
The output is:
Hello World
Note that it is possible to use the + operator to produce the same result:
Dim s3 As String s3 = s1 + s2 Console.WriteLine(s3)
Again, the output is:
Hello World
Relational operators are used to compare two values and then return a Boolean (i.e., true or false). The greater-than operator (>), for example, returns true if the value on the left of the operator is greater than the value on the right. Thus, 5>2 returns the value true, while 2>5 returns the value false.
The relational operators for VB.NET are shown in Table 3-2. This table assumes two variables: bigValue and smallValue, in which bigValue has been assigned the value 100 and smallValue the value 50.
Name |
Operator |
Given this statement: |
The expression evaluates to: |
---|---|---|---|
Equals |
bigValue = 100 bigValue = 80 |
True False |
|
Not Equal |
bigValue <> 100 bigValue <> 80 |
False True |
|
Greater than |
> |
bigValue > smallValue |
True |
Greater than or equal to |
bigValue >= smallValue smallValue => bigValue |
True False |
|
Less than |
bigValue < smallValue |
False |
|
Less than or equal to |
smallValue <= bigValue bigValue =< smallValue |
True False |
Each of these relational operators acts as you might expect. Notice that some of the operators are composed of two characters. For example, the greater than or equal to operator is created using the greater than symbol (>) and the equals sign (=). Notice that you can place these symbols in either order (>= or =>) to form the greater than or equal to operator.
In VB.NET, the equality operator and the assignment operator are represented by the same symbol, the equals sign (=). In the following code line, the symbol is used in each of these ways:
If myX = 5 Then myX = 7
The first use of the = symbol is as the equality operator ("if myX is equal to 5"); the second use is as the assignment operator ("set myX to the value 7"). The compiler figures out how the symbol is to be interpreted according to the context.
Top |