What is the best way to differentiate between derived classes of a base class?

.net, inheritance, oop, polymorphism

Solution

Your design is very likely to be flawed. You should consider making the behavior a method of `BaseClass` and override it in each derived class. You shouldn't check for the actual type of the object.

That is, `ExternalClass` should just call a method declared in `BaseClass` regardless of the actual type. Since the method is overriden by derived classes, the appropriate implementation will be called.

That said, to check if an object is an instance of a type or its derived classes, you can use the `is` operator:

if (obj is DerivedA) // C#
If TypeOf obj Is DerivedA Then ' // VB

If you want to check if the object is an instance of a specific type (and not its derived types):

if (obj.GetType() == typeof(DerivedA)) // C#
If obj.GetType() Is GetType(DerivedA) Then ' // VB

Problem

I have base class `BaseClass` and derived classes `DerivedA`, `DerivedB`, and `DerivedC` that all inherit `BaseClass`. I have another class, `ExternalClass` with a method that accepts a parameter of type `BaseClass`, but is actually passed a derived class. What is the best way to differentiate between these classes in `ExternalClass` if I wanted to perform a different action based on which derived class it received? I was thinking of doing a `Select` but I'm not exactly sure how.

Original source