views:

96

answers:

3

Given this example:

Public Class Car
End Class

Public Class Vovlo
    Inherits Car
End Class

Public Class BMW
    Inherits Car
End Class

When I receive a Car object, how can I determine if the Car object is a Volvo, a BMW or a Car?

I know I can use TypeOf, but when there are several classes that inherits from the Car class, this becomes somewhat cumbersome.

Edit:

This is what I want to acheive:

   Public Sub DoSomething()
        Dim subClassCar As Car.SubClass = DirectCast(car, Car.SubClass)
   End Sub

where Car.CubClass is either a Volvo or BMW if the car object has a subclass, or a car if it do not have a sub class. The problem is how to get the Car.SubClass.

+2  A: 

TypeOf() is the best way - I presume the action you want to take will look something like:

if (MyObject is Volvo) then doSomething(); else if (MyObject is BMW) then doSomething(); end if

If the method you want to execute is already in BMW or Volvo then you don't need to do any type-checking because you know you'll be in the right class. If the method to execute and take action based on the type of car is in the Car base class, then you will need to do the above type-checking but you'd only have to do it in the base class, not in each derived class.

Andy Shellam
I am aware of TypeOf(), but when there are several (>100) classes that inherits the Car object, this is a lot of work, and the code will become messy.
eflles
Sorry I'm still not clear on what you actually want to achieve. If your "DoSomething" method should act differently depending on the type of Car it's given, then create it as an inherited method - e.g. DoSomething on the base class Car, then a DoSomething method on each of the individual classes. When you call DoSomething on a Volvo, it will run Volvo's DoSomething method. This method doesn't need to check the type of object because if it's defined in Volvo, the object is a Volvo.
Andy Shellam
+1  A: 

This is something you really want to avoid. You do so by adding virtual methods to the base class. Discussed in more detail in this article.

Hans Passant
I know that this is not the best way to do things, but I can not redesign the code base.
eflles
Then don't use inheritance, use encapsulation.
Hans Passant
+1  A: 

There are really only the two choices mentioned, either you modify the base class to have a virtual DoSomething method and override it in the subclasses (you can have default functionality in the base class, doesn't have to be abstract), or you write a big conditional statement (I would REALLY not recommend that, goes against OOP)

David