VB.NET is operator

The is operator in VB is used in different ways:
-checking whether object references refer to the same object,
-checking type of a variable against a data type (used with TypeOf)
-checking whether an object reference refers to or associate with any object, and
-restricting values to be matched in Select...Case and it is used with =,>,<,>=, or <= operator.
The examples below demonstrate the uses of is operator as mentioned above.

Checking whether object references refer to the same object:
Module Module1

   Sub Main()
     Dim obj As New Object
     Dim x As Object
     Dim y As Object
     x = obj
     y = obj
     Dim f As Boolean
     f = x Is y
     If f = True Then 'The same object reference
        Console.WriteLine("Both are referring to the same object.")
     Else
        Console.WriteLine("Both are not referring to the same object.")
     End If

     Console.ReadLine()
   End Sub
End Module

Checking type of a object variable against a data type:

Module Module1

   Sub Main()
     Dim obj As Object = "VB"
     Dim tr As Boolean
     tr = TypeOf (obj) Is String 'check against the string type
     If tr Then
        Console.WriteLine("obj is an string type.")
     Else
        Console.WriteLine("obj is not an string type.")
     End If
     Console.ReadLine()
   End Sub
End Module

Checking whether an object variable does not refer to or associate with any object:

Module Module1

   Sub Main()
     Dim x As Object
     If x Is Nothing Then
        Console.WriteLine("Nothing")
     End If
     Console.ReadLine()
   End Sub
End Module

Restricting values to be matched in Select...Case:

Module Module1

   Sub Main()
     Dim num As Integer
     Console.Write("Enter an number greater than zero:")
     num = Integer.Parse(Console.ReadLine())
     Select Case num
        Case Is > 0 : Console.WriteLine("Correct!") 'greater than zero checking
        Case Else : Console.WriteLine("Incorrect!")
     End Select

     Console.ReadLine()
   End Sub
End Module

Posted by: Dara | post date: 02-06-2013 | Subject: VB.NET Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.