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.