Sdílet prostřednictvím


How to: Determine Whether Two Objects Are Identical (Visual Basic)

In Visual Basic, two variable references are considered identical if their pointers are the same, that is, if both variables point to the same class instance in memory. For example, in a Windows Forms application, you might want to make a comparison 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 (Visual Basic) 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 = My.User
objB = New ApplicationServices.User
objC = My.User
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

Tasks

How to: Determine Whether Two Objects Are Related (Visual Basic)

Reference

Object Data Type

Is Operator (Visual Basic)

IsNot Operator (Visual Basic)

Concepts

Object Variables in Visual Basic

Object Variable Values (Visual Basic)

Me, My, MyBase, and MyClass in Visual Basic