Hi all,
I have a question regarding inheritance. I'll use the following code
for an example (its been stripped down to the minimum):
// code start
using System;
class Animal
{
public string name;
public Animal(string pName)
{
name = pName;
}
}
class Dog : Animal
{
public string noise;
public Dog(string pName, string pNoise) : base(pName)
{
noise = pNoise;
}
}
class Cat : Animal
{
public Cat(string pName) : base(pName) { }
}
class MainApp
{
public static void Main()
{
Animal[] myPets = new Animal[3];
Cat animal1 = new Cat("Bob");
Cat animal2 = new Cat("Billy");
Dog animal3 = new Dog("Rover", "bark");
myPets[0] = animal1 as Animal;
myPets[1] = animal2 as Animal;
myPets[2] = animal3 as Animal;
for (int i = 0; i < 3; i++)
{
if (myPets[i] is Cat)
{
Console.WriteLine("Cat: {0}: ",myPets[i].name);
}
else if(myPets[i] is Dog)
{
Dog temp;
Console.WriteLine("Dog: {0}: ", myPets[i].name);
temp = (Dog)myPets[i];
Console.WriteLine(temp.noise);
}
}
}
}
// code finish
So I create an array of base class to store derived types in, but the
'Dog' type has an extra var which I want to access later.
The way I did it above was to recast a type to Dog (which has
previously been Dog but cast to Animal for storage in the array) from
Animal.
My question is, is there a better way to go about this? I'm guessing
(and learning) at the moment so don't know what good practice is.
Another possible solution is to have 'noise' in the base class, but
this makes the inheritence pointless.
Any help would be appreciated,
Chris