Comparison Operators

As in its predecessors, Visual Basic 2010 still defines some comparison operators. Typically comparison operators are of three kinds: numeric operators, string operators, and object operators. Let’s see such operators in details.

Numeric Comparison Operators

You can compare numeric values using the operators listed in Table 4.12.

Table 4.12 Numeric Comparison Operators

image

Such operators return a Boolean value that is True or False. The following code snippet shows an example. (Comments within the code contain the Boolean value returned.)

image

String Comparison Operators

String comparison was discusses in the section “Working with Strings,” so refer to that topic.

Objects Comparison Operators: Is, IsNot and TypeOf

You can compare two or more objects to basically understand if they are or point to the same instance or what type of object you are working with. Basically there are three operators for comparing objects: Is, IsNot, and TypeOf. Is and IsNot are intended to understand if two objects point to the same instance. Consider the following code:

image

firstPerson and secondPerson are two different instances of the Person class. In the first comparison, IsNot returns True because they are two different instances. In the second comparison, Is returns False because they are still two different instances. In the third comparison, the result is True because you may remember that simply assigning a reference type just copies the reference to an object. In this case, both secondPerson and onePerson point to the same instance. The last example is related to the TypeOf operator. Typically you use it to understand if a particular object has inheritance relationships with another one. Consider the following code snippet:

image

We have here an anotherPerson object of type Object, assigned with a new instance of the Person class. (This is possible because Object can be assigned with any .NET type.) The TypeOf comparison returns True because anotherPerson is effectively an instance of Person (and not simply object). TypeOf is useful if you need to check for the data type of a Windows Forms or WPF control. For example, a System.Windows.Controls.Button control in WPF inherits from System.Windows.Controls.FrameworkElement and then TypeOf x is FrameworkElement returns True.

Operators Precedence Order

Visual Basic operators have a precedence order. For further information, refer to the MSDN Library: http://msdn.microsoft.com/en-us/library/fw84t893(VS.100).aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.89.34