c# - public interface introduced in derived class -


two classes, d1 , d2 derive abstract base class b. each of them share common public interface declared in b each of them might have own specific public interface (e.g. d2 has d2.bar() makes sense d2 objects):

public abstract class b {     public int n { get; set; }     public abstract void foo(); }  public class d1 : b {     public override void foo()     {                 } }  public class d2 : b {     public override void foo()     {     }      public void bar()     {                 } } 

i keep mix of derived objects in single collection, (e.g. list) have call common (inherited) methods on objects collection want call bar() on d2 objects only:

        var list = new list<b>();         list.add(new d1());         list.add(new d2());         foreach(var b in list)             if(b d2)                 (b d2).bar(); 

i feel code smell here. downcasting bad idea, making decisions based on type checks bad idea. if move bar() base class, not make sense calling on d1 objects (what implementation of d1.bar() contain?). interface , composition don't either. feel common situation , wondering what's best practice in case? how avoid downcasting allow calling public methods specific derived types?

it sounds me "check , downcast" precisely appropriate given description:

sometimes want call bar() on d2 objects only:

now it's bit of odd requirement, if is requirement, think it's reasonable implement in straightforward fashion rather adding no-op implementations operations don't make sense on base class.

however, i'd go differently:

foreach (var d2 in list.oftype<d2>()) {     d2.bar(); } 

now says mean :)


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -