Is it a good practice to have a list containing objects of derived types and then filtering it by type checking when need to call methods specific for one of the types? From what I read typechecking is some kind of code smell and it indicates that OOP isn't fully used.
I use common list for object of all subtypes because I want to call some common methods on all objects. But some methods are specific for some subtype and if I want to invoke the method I need to filter out objects by type.
public abstract class ParentType { public abstract void CommonMethod(); } public class DerivedTypeA : ParentType { public override void CommonMethod() { //do something } public void TypeASpecificMethod() { //do something } } public class DerivedTypeB : ParentType { public override void CommonMethod() { //do something } public void TypeBSpecificMethod() { //do something } } static void Main() { List<ParentType> objects = new List<ParentType>() { new DerivedTypeA(), new DerivedTypeA(), new DerivedTypeB(), new DerivedTypeB() } //Call common method on all objects in a list foreach(var obj in objects) { obj.CommonMethod(); } //Call only specific method for DerivedTypeA objects foreach(var obj in objects) { if(obj is DerivedTypeA derivedAObj) //type checking needed { derivedAObj.TypeASpecificMethod(); } } }
CommonMethodinDerivedTypeAjust callTypeASpecificMethod?