0

I'm trying to write a program in c# (Visual studio 2010-windows form application) that calculates the area and the perimeter of a rectangle but using the Rectangle class. I have form1 with 2 textboxes (length and width of the rectangle)and 2 labels with the results(area and perimeter). This is the code:

namespace Rectangle
{
public partial class Form1 : Form
{
    Rectangle r;
    public Form1()
    {
        InitializeComponent();

    }

    private void btnArea_Click(object sender, EventArgs e)
    {
        if (txtWidth.Text.Length == 0 || txtLength.Text.Length == 0)
            MessageBox.Show("Insert something in the textboxes!", "Attention!");
        else
            lblArea.Text = r.Area().ToString();

    }

    private void btnPerimeter_Click(object sender, EventArgs e)
    {
        //r.width = Convert.ToInt32(txtWidth.Text);
        //r.length = Convert.ToInt32(txtLength.Text);
         if (txtWidth.Text.Length == 0 || txtLength.Text.Length == 0)
            MessageBox.Show("Insert something in the textboxes!", "Attention!");
        else

            lblPerimeter.Text = r.Perimeter().ToString();
    }

}
}

My class code is:

namespace Rectangle
{ 
class Rectangle
{
    static int length, width;
    public int Length
    {
        get { return length; }
        set { length = value; }
    }

    public int Width
    {
        get { return width; }
        set { width = value; }
    }
    public int Perimeter()
    {
        return 2 * (length + width);
    }

    public int Area()
    {
        return length * width;
    }
}
}

I have an exception ("Object reference not set to an instance of an object") at this lines:

lblPerimeter.Text = r.Perimeter().ToString();
lblArea.Text = r.Area().ToString();

How to fix it? The program doesn't calculates the area neither the perimeter. Thank you 4 help!

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
ghostlegend
  • 512
  • 10
  • 19
  • 1
    From that line of code, it can mean any of these 5 things: (1) `r` is null, (2) `txtWidth` is null, (3) `txtLength` is null, (4) `txtWidth.Text` is null, or (5) `txtLength.Text` is null. I'd step through in the debugger and you'll have your answer pretty quickly. – Ed Gibbs Nov 13 '14 at 18:02
  • [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). – CodeCaster Nov 13 '14 at 18:06

1 Answers1

4

You must Create an instance From Rectangle Class as below:

<!-- language: c# -->
Rectangle r = new Rectangle();
Shiva
  • 20,575
  • 14
  • 82
  • 112
Dotnetter
  • 261
  • 1
  • 5