Let's say I have following classes:
public class Animal {
public string name;
public int age;
public bool canBark;
}
public class Dog : Animal {
}
And instantiate an Animal
like this:
Animal a = new Animal();
Is there anyway of downconverting this instance to a Dog
instance after it's created? Or am I forced to recognize that my Animal
is a Dog
when I create it? The reason I'm having this problem is because my instance is created by calling a factory class that returns a type based on a JSON file that I feed it. The canBark
attribute value is calculated by looking at several seemingly unrelated fields in that file. It seems it make more sense to determine that something is a Dog
by looking at the canBark
field, rather than those JSON fields.
public class AnimalFactory{
public static Animal Create(JObject json){
Animal a = new Animal();
a.canBark = (json["someField"]["someOtherField"].ToString() == "abc")
.....
}
I kind of solve this problem right now by having a constructor in the Dog
class that takes an Animal
as its argument and simply assigns the values of that instance's variables to its own. But this is not a very flexible way as I would need to add a line in each subclass constructor everytime I add a field.
So, is the best way of determining the type by moving that decision to the instance creation or is there some other way?