Home > database >  How can I directly access my base class property in the derived class without using methods or const
How can I directly access my base class property in the derived class without using methods or const

Time:08-16

class Animal
    {
        public bool isHungry { get; set; }
        public int Age { get; set; }
        public string Name { get; set; }
    }    
class Dog : Animal
    {
        Age = 5; //Gives error, "Age doesnt exist in current context"
        public Dog()
        {
            Age = 5;//Works fine
            Console.WriteLine("Dog");
        }
    }

I want to access the public properties directly, is it not possible?

CodePudding user response:

Code must be within methods - if you want to set a default value for all Dog instances then the constructor is the proper place to do that.

You could make the base property virtual and then override it in Dog with a default value:

class Animal
{
    public bool isHungry { get; set; }
    public virtual int Age { get; set; }
    public string Name { get; set; }
}    
class Dog : Animal
{
    public override int Age {get; set;} = 5; 
    public Dog()
    {
        Console.WriteLine("Dog");
    }
}

but that seems like overkill in this simple example.

CodePudding user response:

D Stanley is totally right. Another way to do it is to use new keyword. This is a little bit cleaner in my opinion but totally depends on the context and problem.

class Dog : Animal
{
    public new int Age = 5;
}

CodePudding user response:

Presumably, not all animals would have the same age (5 in this case). Set your properties via the constructor, or if they have public setters, instantiate an instance of Dog and then set its Age property.

public abstract class Animal
{
    protected Animal()
    {
    }

    public int Age { get; set; }
}    

public class Dog : Animal
{
    public Dog(int age)
    {
        this.Age = age;
    }

    public override string ToString()
    {
        return $"{nameof(Dog)}: {nameof(Age)} - {this.Age}";
    }
}
  • Related