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

Why I can't access child field when use inheritance in C#?

using System;
class MyClass
{  
    public static void Main()
    {
        Student a = new Student();
        Person y = new Gamer();

        Console.WriteLine(a.X);
        Console.WriteLine(y.X); <=== Error here
    }
}

abstract class Person
{
    public abstract void Display();
}

class Student : Person
{
    public int X { get; set; } = 1;
    public override void Display()
    {
        Console.WriteLine("Student");
    }
}

class Gamer : Person
{
    public int X { get; set; } = 1;
    public override void Display()
    {
        Console.WriteLine("Gamer");
    }
}

Hi,
I’ve tried to inherit Student, Gamer class from Person. In the code above, I don’t know why y object cannot access to X – property of Gamer class.

Please, help me to explain. Thanks

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

>Solution :

just edit this line:

// Person y = new Gamer(); ==> Person does not have a field named X
Gamer y = new Gamer();
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