Reputation: 21
Let's assume I have a class Animal
and a subclass Dog
. The subclass Dog
has a property which the class Animal
doesn't have (let's assume the property is Age
and this property hasn't been defined in the Animal
class before).
Now when I have:
Animal animal;
and later I recognize that my animal is a dog:
animal = new Dog();
How can I access the age of the dog now like:
int age = animal.Age;
Thanks in advance!
Upvotes: 0
Views: 255
Reputation: 6746
You need to cast your animal
back to a Dog
to access the properties of it. You can do this safely with either:
as
with null
check:
Dog dog = animal as Dog;
if (dog != null) { /*animal was Dog access properties here*/ }
is
with explicit cast:
if (animal is Dog)
{
Dog dog = (Dog)animal;
}
However, this downcasting looks like a code smell, you might need to consider a redesign.
Upvotes: 1
Reputation: 17004
Simple cast it using (Dog)animal
.
In these cases I like to use the as
cast:
var probablyDog = animal as Dog;
if (probablyDog != null)
{
//indeed dog
probablyDog.Age;
}
if probablyDog
is null, it is no dog or animal
is null.
Upvotes: 0