Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the spirit of the c# question..

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

like image 280
brasskazoo Avatar asked Jun 16 '09 23:06

brasskazoo


People also ask

What is the difference between Instanceof and isInstance?

The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.

What is java Instanceof operator?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. Its syntax is. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

Does Instanceof work for subclasses?

As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface.

Is instance of integer java?

As the name suggests, instanceof means an instance (object) of a class. Primitive datatypes are not instances. Just because java is able to automatically convert an int to an Integer, doesnt mean that the int itself is actually an Integer.


1 Answers

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.

like image 175
Andrew Avatar answered Nov 21 '22 13:11

Andrew