How to: Test Whether Two Objects Are the Same (Visual Basic)

If you have two variables that refer to objects, you can use either the Is or IsNot operator, or both, to determine whether they refer to the same instance.

To test whether two objects are the same

  • Use the Is Operator (Visual Basic) or the IsNot Operator (Visual Basic) with the two variables as operands.

    Public Sub processControl(ByVal f As System.Windows.Forms.Form, 
        ByVal c As System.Windows.Forms.Control)
        Dim active As System.Windows.Forms.Control = f.ActiveControl
        If (active IsNot Nothing) And (c Is active) Then
            ' Insert code to process control c
        End If
        Return
    End Sub
    

You might want to take a certain action depending on whether two objects refer to the same instance. The preceding example compares control c against the active control on form f. If there is no active control, or if there is one but it is not the same control instance as c, then the If statement fails and the procedure returns without further processing.

Whether you use Is or IsNot is a matter of personal convenience to you. One might be easier to read than the other in a given expression.

See Also

Concepts

Comparison Operators in Visual Basic