Export (0) Print
Expand All

How to: Determine Whether Two Objects Are Identical 

Visual Basic considers two objects to be identical if their pointers are the same, that is, if both variables point to the same class instance in memory. You might want to make this comparison, for example, to determine whether the current instance (Me) is the same as a particular instance such as Form2.

Visual Basic provides two operators to compare pointers. The Is Operator (Visual Basic) returns True if the objects are identical, and the IsNot Operator returns True if they are not.

Determining if Two Objects Are Identical

To determine if two objects are identical

  1. Set up a Boolean expression to test the two objects.

  2. In your testing expression, use the Is operator with the two objects as operands.

    Is returns True if the objects point to the same class instance.

Determining if Two Objects Are Not Identical

Sometimes you want to perform an action if the two objects are not identical, and it can be awkward to combine Not and Is, for example If Not obj1 Is obj2. In such a case you can use the IsNot operator.

To determine if two objects are not identical

  1. Set up a Boolean expression to test the two objects.

  2. In your testing expression, use the IsNot operator with the two objects as operands.

    IsNot returns True if the objects do not point to the same class instance.

Example

The following example tests pairs of Object variables to see if they point to the same class instance.

Dim objA, objB, objC as Object
objA = Me
objB = New System.Windows.Forms.Form()
objC = Me
MsgBox("objA different from objB? " & CStr(objA IsNot objB))
MsgBox("objA identical to objC? " & CStr(objA Is objC))

The preceding example displays the following output.

objA different from objB? True

objA identical to objC? True

See Also

Community Additions

ADD
Show:
© 2014 Microsoft