John Doe
John Doe

Reputation: 21

How to access properties from base class?

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

Answers (2)

TheLethalCoder
TheLethalCoder

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

Christian Gollhardt
Christian Gollhardt

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

Related Questions