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!