Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I directly access my base class property in the derived class without using methods or constructors?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading