c# - How do I turn an Animal instance into a Dog instance? -


say have following classes:

class animal {     public long id { get; set; }     public string name { get; set; } }  class dog:animal {     public void sniffbum()     {         console.writeline("sniff sniff sniff");     } } 

if have instance of animal, how cast dog? this:

animal = new animal(); if ( logic determine animal dog ) {     dog d = (dog)a;     d.sniffbum(); } 

essentially can't use interfaces. have animal object coming out of database that. dog doesn't have more parameters animal has, new methods.

i create new dog object, , pass values across, (or have constructor takes type animal), seems messy.

casting checks not work if animal instance has never been dog instance.

you may want @ decorator pattern, allow add dog methods animal instance. essentially, dog , animal both have ianimal interface. dog class takes animal instance in constructor , keeps internal reference. dog's ianimal implementation defers animal instance references (which allows dog cast ianimal , behave wrapped animal polymorphism). dog has additional methods dog-specific.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -