This is how I do it currently:
ref class Base abstract {};
ref class ConcreteClass1 : public Base {};
ref class ConcreteClass2 : public Base {};
(...and even more...)
void DoStuff(Base ^base)
{
System::Type ^type = base->GetType();
System::String ^name = type->Name;
if(name == "ConcreteClass1")
DoOtherStuff((ConcreteClass1 ^) base);
else if(name == "ConcreteClass2")
DoOtherStuff((ConcreteClass2 ^) base);
(...and even more...)
}
Is there a more “elegant” way to do this?
With my approach, I have to add a new else if for every new Concrete Class, which makes me feel like one of the examples on thedailywtf.com.
Well, one simple thing you could do to make this more elegant would be to compare the types directly instead of using strings and type names:
However, this has quite a bit of “code smell” to it. Typically, the entire point of using abstract classes is to allow for polymorphism – if you can make DoOtherStuff a virtual function on each type, you could just do:
And the appropriate method will get called for you…