What is the VB equivalent of Java's instanceof and isInstance()?
Asked Answered
D

4

14

In the spirit of the c# question..

What is the equivalent statements to compare class types in VB.NET?

Dodge answered 16/6, 2009 at 23:56 Comment(0)
G
22

Are you looking for something like TypeOf? This only works with reference types, not int/etc.

If TypeOf "value" Is String Then
     Console.WriteLine("'tis a string, m'lord!")

Or do you want to compare two different instances of variables? Also works for ref types:

Dim one As Object = "not an object"
Dim two As Object = "also not an object, exactly"
Dim three as Object = 3D

If one.GetType.Equals( two.GetType ) Then WL("They are the same, man")
If one.GetType Is two.GetType then WL("Also the same")
If one.GetType IsNot three.GetType Then WL("but these aren't")

You could also use gettype() like thus, if you aren't using two objects:

If three.GetType Is gettype(integer) then WL("is int")

If you want to see if something is a subclass of another type (and are in .net 3.5):

If three.GetType.IsSubclassOf(gettype(Object)) then WL("it is")

But if you want to do that in the earlier versions, you have to flip it (weird to look at) and use:

If gettype(Object).IsAssignableFrom(three.GetType) Then WL("it is")

All of these compile in SnippetCompiler, so go DL if you don't have it.

Gerkman answered 17/6, 2009 at 0:1 Comment(0)
D
4
TypeOf obj Is MyClass
Disruptive answered 16/6, 2009 at 23:58 Comment(0)
U
1

Not sure when it was implemented but VB now has Type.IsInstanceOfType():

"Returns true if the current Type is in the inheritance hierarchy of the object represented by o, or if the current Type is an interface that o implements..."

Example:

Dim arr(10) As Integer
If GetType(Array).IsInstanceOfType(arr) Then _
    Console.WriteLine("Is int[] an instance of the Array class? {0}.",
                       GetType(Array).IsInstanceOfType(arr))

Output: Is int[] an instance of the Array class? True.

Unbounded answered 29/6, 2022 at 19:58 Comment(0)
W
0

The VB equivalent to your linked question is almost identical:

Dim result As Boolean = obj.GetType().IsAssignableFrom(otherObj.GetType())
Window answered 16/6, 2009 at 23:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.