Types of Operators in Visual Basic

In this second part of a two-part article, you will learn about comparison operators, the like operator, and more. It is excerpted from chapter five of the book Visual Basic 2005 in a Nutshell, Third Edition, written by Tim Patrick, Steven Roman, Ph.D., Ron Petrusha and Paul Lomax (O’Reilly; ISBN: 059610152X). Copyright © 2006 O’Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O’Reilly Media.

Comparison Operators

There are three main comparison operators: < (less than), > (greater than), and = (equal to). They can be used individually, or any two operators can be combined with each other to form other comparison operators. The general syntax is:

  result = expression1 <operator> expression2

The result is a Boolean value of True or False.

The following list indicates the condition required with each VB comparison operator to return a value of True.

= (Equal To)
   
True if expression1  is equal to expression2

< (Less Than)
   
True if expression1  is less than (and not equal to)
  expression2

> (Greater Than)
  True if expression1  is greater than (and not 
    equal to) expression2

<= (Less Than or Equal To)
   True if expression1 is less than or equal to
   expression2

>= (Greater Than or Equal To)
   True
if expression1  is greater than or equal to
   expression2

<> (Not Equal To)
   
True if expression1  is not equal to expression2

Comparison operators can be used with both numeric and string expressions. If one expression is numeric and the other is a string, the string is first converted to a number of type Double (nonnumeric strings throw an exception). If both expression1 and expression2 are strings, the "greatest" string is the one that appears second in sort order. The sorting is based on the current character code page in use by the application, the region-specific locale information, and the OptionCompare setting. If that setting is Binary, the comparison is case-sensitive, whereas a setting of Text results in a case-insensitive comparison.

New in 2005. There are two "hidden" operators in Visual Basic: IsTrue(arg) and IsFalse(arg). They return a Boolean value that indicates whether the supplied argument is True or False, respectively. You cannot use them directly in your code, but they do exist, beginning in the 2005 release of Visual Basic, to support operator overloading. This is covered in the "Operator Overloading" section later in this chapter.

{mospagebreak title=The Like Operator}

The Like operator is used to match a string against a pattern. It compares a string expression or literal with a string pattern expression and determines whether they match (the result is True) or not (the result is False). For example:

  If (testString Like "[A-Z]#") Then

matches a capital letter followed by a digit.

For details on the use of this operator, including special characters used in the pattern string, see the "Like Operator" entry in Chapter 12.

Object Operators

Visual Basic includes five operators that return results based on an operand’s object properties.

Is

The Is operator determines whether two object reference variables refer to the same object instance.

  result = object1 Is object2

If both object1 and object2  refer to the same object instance, the result is True; otherwise, the result is False. You can also use the Is operator to determine if an object variable refers to a valid object. This is done by comparing the object variable to the Nothing keyword:

  If (customerRecord Is Nothing) Then

The result is True if the object variable does not hold a reference to any object.

IsNot

New in 2005. The IsNot operator is equivalent to the Is operator used with the Not logical operator. The statement:

  If (customerRecord IsNot Nothing) Then

is the same as:

  If Not (customerRecord Is Nothing) Then

There is no functional difference between the two statements. The IsNot operator was added to VB to make such statements more readable.

TypeOf

The TypeOf operator determines if an object variable is of a specific data type. It is always used with the Is operator. (It does not work with the new VB 2005 IsNot operator.) The following statement tests an object variable to see if it is an Integer.

  If (TypeOf someNumber Is Integer) Then

AddressOf

The AddressOf operator returns a procedure delegate that can be used to reference a procedure through a variable. In VB 6, the AddressOf operator returned a function pointer, the memory address of the function. While the .NET version of this operator serves a similar purpose, it does not return a memory address. The .NET Framework reserves the right to move objects (including procedures) to new memory locations at any time, so you cannot depend on the memory address.

For details on the AddressOf operator, including usage information, see the AddressOf Operator entry in Chapter 12.

GetType

The GetType operator returns a System.Type object that contains information about the data type of the operand. You cannot use expressions or variables as operands; you must pass a data type itself. You can use VB data types (like Integer or String), .NET core types (like System.Int32), or the name of any class, structure, or similar construct. For example:

  result = GetType(Integer)

returns a System.Type object that provides information about the System.Int32 data type, which is the true data type of the Visual Basic Integer data type.

{mospagebreak title=Operator Overloading}

New in 2005. Although Visual Basic is as powerful as any other .NET language, early versions lacked specific features found in some other .NET languages (just as VB had features absent from those languages). One feature present in C#, but absent in VB, was operator overloading, the ability to redefine unary and binary operators and give them special uses when working with specific classes or structures. As of the 2005 release of Visual Basic, operator overloading is now part of the Visual Basic experience.

To perform operator overloading, you simply create a special procedure in your class with the name of the operator, indicate the data type(s) of the operand(s) and the data type of the return value, make it Public and Shared, and it’s ready to use. The class (or structure) you put the procedure in is significant. At least one operand for the operator must be of the class data type in which the procedure appears. For the special CType unary operator, either the operand or its return value must use the data type of the class that includes the procedure.

All overloaded operator procedures share a common syntax.

  Public Shared [otherModifiers] Operator operatorSymbol _
       
(ByVal operand1 As dataType[, ByVal operand2 As dataType]) _
       
As returnDataType
   
‘ —– Statements of the operator procedure.
  End Operator

As an example, consider a class named LandRegion that defines the boundaries of a piece of land. Since you would like to merge two records together into a larger tract of land using the + addition operator, you define the following procedure in the LandRegion class.

  Public Shared Operator +(ByVal firstArea As LandRegion, _
       
ByVal secondArea As LandRegion) As LandRegion
   
‘ —– Merge two land regions together.
   
Dim combinedRegion As New LandRegion
   
‘ …more code here…
   
Return combinedRegion
  End Operator

Since the routine is Public, it is available to your entire program. Since it is Shared, the routine exists even without the presence of any specific instance of the class (although at least one operand must be of that class). The defined operands must always be passed ByVal. Using this operator is simple.

  Dim mainCity As New LandRegion
  Dim unincorporatedArea As New LandRegion
  Dim annexation As LandRegion

  ‘ …fill in mainCity and unincorporatedArea members, then…
  annexation = mainCity + unincorporatedArea

For binary operators, only one of the operands has to match the enclosing class or structure type.

  Public Shared Operator +(ByVal wholeOrder As OrderRecord, _
       
ByVal orderDetailItem As DetailRecord) As OrderRecord
   
‘ —– Append a new product item onto the order.
   
‘ …more code here…
  End Operator

Table 5-1 describes the operators that can be overloaded.

Table 5-1. Operators that can be overloaded

Operator

Description

+

Unary Plus operator. It differs from the binary addition operator in that you supply only one operand in the procedure signature.

-

Unary Negation operator. It differs from the binary subtraction operator in that you supply only one operand in the procedure signature.

Not

Bitwise Negation operator. For overloading, this is a bitwise operation only, not logical.

IsTrue

If you overload the Oroperator in a class, overloading the IsTrueoperator in the same class opens up the use of the OrElse operator with the class. You must also overload the IsFalse operator. The over-load procedure’s return type must be Boolean.

IsFalse

If you overload the Andoperator in a class, overloading the IsFalseoperator in the same class opens up the use of the AndAlsooperator with the class. You must also overload the IsTrueoperator. The overload procedure’s return type must be Boolean.

+

Binary Addition operator. It differs from the unary plus operator in that you supply two operands in the procedure signature.

-

Binary Subtraction operator. It differs from the unary negation operator in that you supply two operands in the procedure signature.

*

Multiplication operator.

/

Division operator.

Integer Division operator.

Mod

Modulo operator.

&

Concatenation operator.

^

Exponentiation operator.

<<

Shift Left operator. The second operator must use the Integerdata type.

>>

Shift Right operator. The second operator must use the Integerdata type.

=

Equal To comparison operator. You must also overload the <>Not Equal To operator.

<

Less Than comparison operator. You must also overload the >Greater Than operator.

>

Greater Than comparison operator. You must also overload the <Less Than operator.

<=

Less Than or Equal To comparison operator. You must also overload the >=Greater Than or Equal To operator.

>=

Greater Than or Equal To comparison operator. You must also overload the <=Less Than or Equal To operator.

<>

Not Equal To comparison operator. You must also overload the =Equal To operator.

And

Bitwise Conjunction operator. For overloading, this is a bitwise operation only, not logical.

Or

Bitwise Disjunction operator. For overloading, this is a bitwise operation only, not logical.

Xor

Bitwise Exclusion operator. For overloading, this is a bitwise operation only, not logical.

Like

Pattern Comparison operator.

CType

Unary Conversion operator. Used to convert data from one data type (or class or structure) to another. You must include either the Narrowingor Wideningkeyword in the definition of the overload, some-where between the Sharedand Operatorkeywords. These modifiers tell the compiler what type of conversion is allowed. Narrowing conversions may fail if the destination data type cannot support the value of the source data type. Either the operand or the return type of the overload procedure must be of the class or structure that contains the procedure.

When you overload operators, you can define them to do whatever you want with the source classes in question. In fact, you could create a class where the normal understandings of addition and subtraction were reversed. However, such practices will make the code more difficult to understand and debug.

For further details about operator overloading, see the "Operator Statement" entry in Chapter 12.

{mospagebreak title=Operator Precedence}

If you include more than one operator in a single line of code, you need to know the order in which VB will evaluate them. Otherwise, the results may be completely different from what you intended. For instance, the following statement:

  x = 5 + 3 * 7

could be interpreted as:

  x = (5 + 3) * 7 ‘ –> 56

or as:

  x = 5 + (3 * 7) ‘ –> 26

The rule that defines the order in which a language processes operators is known as the order of precedence. If the order of precedence results in operations being evaluated in an order other than the intended one, you can explicitly override the order of precedence through the use of parentheses. Indeed, complex (or even relatively simple) expressions should include parentheses to avoid any compiler misinterpretation or human confusion. (By the way, the example, once parentheses are removed, evaluates to 26.)

When multiple operators appear at the same level of evaluation (that is, they are not subgrouped with parentheses), they are processed in a specific order of precedence. In some instances, multiple operators appear at the same level of precedence (as are * and /). They are treated as equals as far as precedence is concerned. The following list indicates the order of precedence in evaluation, from first to last.

  1. Exponentiation (^).
  2. Negation (-).
  3. Multiplication and division (*, /).
  4. Integer division ().
  5. Modulo operator (Mod).
  6. Addition/concatenation and subtraction (+, -).
  7. String concatenation (&).
  8. New in 2003. Arithmetic bit shift (<<, >>).
  9. Comparison and object operators (=, <>, <,  <=, >, >=, Like, Is, IsNot, TypeOf); the = operator in this list is the Equal To comparison operator, not the assignment operator. New in 2005. The IsNot operator is new in the 2005 release of VB.
  10. Logical and bitwise negation (Not).
  11. Logical and bitwise conjunction (And, AndAlso). New in 2005. The AndAlso operator is new in the 2005 release of VB.
  12. Logical and bitwise disjunction (Or, OrElse, Xor ). New in 2005. The OrElse operator is new in the 2005 release of VB.

Since the AddressOf and GetType operators are implemented like functions, they fall outside of the order of precedence rules for operators.

If multiple operators of the same order of precedence appear at the same level of evaluation, they are processed from left to right.

One thought on “Types of Operators in Visual Basic

  1. This article is an excerpt from the book “Visual Basic 2005 in a Nutshell, Third Edition,” published by O’Reilly. We hope you found it to be enjoyable and educational. Please let us know what you thought of it, and if you would like to see more content of this nature.

[gp-comments width="770" linklove="off" ]