-2

I am new to C# and i am having issues understanding this error. I have a class A which has a constructor that initializes a property which would be common to 2 of its children

public class A
{
  Property P1;
  public A(Property p1)
 {
    this.p1=p1;
 }
 }

I have a class B which derives from this class and its constructor initializes its own parameters as well

 public class B : A
 {
     Property p2:
     Property p1;
     public B(Property p2): base(p1)
    {
        this.p2=p2;
    }
   }
 }

I get an error in the constructor B "An object reference is required for the non static field , method, or property" My goal is to just initialize property P2 in constructor B .I added the base (p1) as i got an error that there is no actual parameter which corresponds to the formal parameter. What is the right way to initialize both the parameters?

novice_coder
  • 147
  • 2
  • 10
  • 1
    You cant pass in instance members to the base constructor, they need to be static or available through the derived constructor (as parameters), more than likely you want `public B(Property p2): base(p2)` – TheGeneral Sep 14 '20 at 03:38
  • Right. And the reason, or part of it, is that there is no instance of derived available _yet_ at the point where `base(p2)` is. It is under construction. – Aluan Haddad Sep 14 '20 at 03:50

1 Answers1

2

Your B constructor should look like this:

 public B(Property p1, Property p2): base(p1)

So B accepts p1 and p2, and p1 is passed to the base constructor in A.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86