Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance : does not contain a definition for and no extension method accepting a first argument

Tags:

c#

inheritance

abstract class Parent
{
        protected string attrParent;

        public AttrParent { get; protected set }

        public Parent(string sParent)
        {
            AttrParent = sParent;
        }
}

class Child : Parent
{
        private string attrChild;

        public AttrChild { get; private set }

        public Child(string sParent, string sChild) : base(sParent)
        {
            AttrChild = sChild;
        }
}

class Program
{
        static void Main(string[] args)
        {
            Parent p = new Child();

            p.AttrChild = "hello";
        }
}

When I run this program, I get the following error :

'Example.Parent' does not contain a definition for 'AttrChild' and no extension method 'AttrChild' accepting a first argument of type 'Example.Parent'"

Can anybody explain why this is?

like image 712
user Avatar asked Nov 19 '25 00:11

user


1 Answers

The moment you assign Child instance to variable typed as Parent you can only access members declared on Parent.

You'd have to downcast it back to Child to access Child-only members:

Parent p = new Child();

Child c = (Child)p;
c.AttrChild = "hello";

That cast might fail at runtime, because there might be a different class that inherits Parent.

like image 57
MarcinJuraszek Avatar answered Nov 21 '25 12:11

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!