1

I want to find out if two objects have the same type. I've tried

if TypeOf X = TypeOf Y

and

if TypeOf X is TypeOf Y

but neither of these are valid VB

Is there a way of doing this in one line, or do I just have to make code for each possible type?

if (TypeOf X is Type1 AndAlso TypeOf Y is Type1)
OrElse (TypeOf X is Type2 AndAlso TypeOf Y is Type2)
...
Peter
  • 151
  • 6
  • 3
    Possible duplicate of [How to check if an object is a certain type](https://stackoverflow.com/questions/6580044/how-to-check-if-an-object-is-a-certain-type) – the_lotus Nov 24 '17 at 16:44
  • 1
    x.GetType() = y.GetType(). Or x.GetType().IsAssignableFrom(y.GetType()). Or TryCast(x, y.GetType()). Hard to guess what you actually want when you don't tell us why you need this. – Hans Passant Nov 24 '17 at 18:18
  • In my opinion, it's not a duplicate, since that other question is how to check if an object is of a particular known type rather than checking to see if two different objects are of the same type. Similar, and helpful, but not fully the same. – Steven Doggart Nov 24 '17 at 18:35

1 Answers1

1

As mentioned by Hans in the comments, if you need to check to see if two objects are exactly the same type as each other, you can do so like this:

If x.GetType() = y.GetType() Then

But, that may not be exactly what you need. If you need to know if the one can be cast into the type of the other (x is an instance of derived class and y is an instance of its base class), you could do that like this:

If x.GetType().IsAssignableFrom(y.GetType()) Then
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
  • Thanks Hans and Steven. That answers my question completely. It's Hans's solution I need as I want to make sure which of an inheritance tree my object belongs to. But Steven's answer will also be useful later, I'm sure. I'd forgotten (or never learnt) about GetType. – Peter Nov 25 '17 at 18:04