Reputation: 6846
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.
Upvotes: 2
Views: 929
Reputation: 8926
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)
Upvotes: 1
Reputation: 941873
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.
Upvotes: 1
Reputation: 15535
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.
Upvotes: 2