Home > Net >  An object reference is required for the nonstatic field, method, or property 'member'. err
An object reference is required for the nonstatic field, method, or property 'member'. err

Time:03-18

Question:

Create a base class that contains the protected variable - rectangle At the base. Create a successor class to the rectangle that additionally Contains: private variables - height and area of ​​a rectangle; Open A method that calculates and returns the area of ​​a rectangle. Home In the program, create an object with an inherited class type and call it Method.

So problem is shown on the picture, and i have no idea, what's wrong , or what the problem is.

This is the error:

This is the error

namespace _4_2_Rectangle_
{
    class Base
    {
        protected double fudze;
        public Base(double fudze)
        {
            this.fudze = fudze;
        }
    }

    class Rectangle : Base
    {
        private double height;
        private double Area;

        public Rectangle(double height): base(fudze)
        {
            this.height = height;
        }

        public double area()
        {
            Area = height * fudze;
            return Area;
        }
    }
}


namespace _4_2_Rectangle_
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        { 

            double fudze, height, Area;

            fudze = double.Parse(textBox1.Text);
            height = double.Parse(textBox2.Text);

            Base obj_2 = new Base(fudze);
            Rectangle obj_1 = new Rectangle(height);

            Area = obj_1.area();
            label4.Text = Area.ToString();
          
            
        }
    }
}

This one is second class.

CodePudding user response:

The problem is that "fudze" is not defined. You are creating the Rectangle at this moment and trying to pass a parameter to base class, been the parameter a field of this base class

public Rectangle(double height): base(fudze)
{
   this.height = height;
}

Try with:

   public Rectangle(double fudze, double height): base(fudze)
   {
      this.height = height;
   }

CodePudding user response:

It seems, that you should have two paramters in Rectangle;s constructor:

    public Rectangle(double fudze, double height): base(fudze)
    {
        this.height = height;
        //DONE: you can compute Area in the constructor as well:
        Area = height * fudze;
    }

Then when creating Rectangle instance you should provide two parameters:

    private void button1_Click(object sender, EventArgs e)
    { 
        double fudze, height, Area;

        fudze = double.Parse(textBox1.Text);
        height = double.Parse(textBox2.Text);

        //DONE: Rectangle wants both fudze and height
        Rectangle obj_1 = new Rectangle(fudze, height);

        Area = obj_1.area();
        label4.Text = Area.ToString();
    }
  • Related