Is Operator

   
Is Operator

Syntax

   object1   Is   object2   
object1 (required; Object or any reference type)
object2 (required; Object or any reference type)

Return Value

Boolean

Description

Compares two object variables or reference variables to determine whether they reference the same object

Rules at a Glance

  • Both object1 and object2 must be reference-type variables. This includes string variables, object variables, and array variables, for instance.

  • The operation returns a result of True if the references are identical and False if they are not.

  • It is also possible to determine whether an object contains a valid reference by replacing object2 with the special Nothing keyword. For example:

     If   oDrive   Is Nothing Then 

    returns True if oDrive does not refer to an object and False if it does. This is the only method that should be used to test for an uninitialized object reference.

Programming Tips and Gotchas

  • You can call the IsReference function to ensure that both object1 and object2 are reference types.

  • You may wonder why there is a special Is operator for reference types. When you perform a comparison of scalar variables, you want to know if their values are the same. But in the case of objects, you want to know if two references point to a single object. (Since many objects have identical property values, a test for equal values is meaningless.) Hence, the Is operator is used for this purpose.

  • Typically, the Is operator is used in an If...Then...Else construct to take some action if two reference-type variables are the same or if a reference type variable does not point to a valid object.

  • The Is operator also can be used with the TypeOf operator and the If...Then... construct to determine the type of an object variable. For example:

     If TypeOf(sName) Is String Then 

    If the variable passed to the TypeOf operator is a reference type, it must hold a valid object reference in order for the type comparison to be True .

  • The Is operator reports that uninitialized reference types are equal. For instance, the Is operator reports that all of the following are equal:

     Dim obj1 As Object Dim obj2 As Object  If obj1 Is obj2 Then             ' Evaluates to True Dim arrSt1(  ) As String Dim arrSt2(  ) As String If arrSt1 Is arrSt2 Then         ' Evaluates to True Dim str1 As String  Dim str2 As String If str1 Is str2 Then              ' Evaluates to True 

VB.NET/VB 6 Differences

In VB.NET, strings and arrays are reference types. In VB 6, strings and arrays are not reference types and, therefore, cannot be used with the Is operator.

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net