How do I turn an Animal instance into a Dog instance?

c#, inheritance, oop

Solution

Casting checks will not work if the `Animal` instance has never been a `Dog` instance.

You may want to look at the Decorator Pattern, which will allow you to add `Dog` methods to an `Animal` instance. Essentially, `Dog` and `Animal` both have the `IAnimal` interface. The `Dog` class takes an `Animal` instance in the constructor and keeps an internal reference. The `Dog`'s `IAnimal` implementation simply defers to the `Animal` instance it references (which allows the `Dog` to be cast to `IAnimal` and behave like the wrapped `Animal` for polymorphism). The `Dog` also has additional methods that are Dog-specific.

Problem

Say I have the 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 I have an instance of `Animal`, how do I cast it to a `Dog`? Something like this: ``` Animal a = new Animal(); if ( some logic to determine that this animal is a dog ) { Dog d = (Dog)a; d.sniffBum(); } ``` Essentially I can't use interfaces. I will always have an `Animal` object coming out of my database like that. `Dog` doesn't have any more parameters than `Animal` has, only new methods. I could just create a new `Dog` object, and pass the values across, (or have a constructor that takes a type `Animal`), but this just seems messy.

Original source

Related problems