user3308294
user3308294

Reputation: 1

Setting up a display method to present my data from objects

private void shapeBuilderButton_Click(object sender, EventArgs e)
{
    // Objects of shapes

    Rectangle rectangle1 = new Rectangle(20, 30);
    Square square1 = new Square(25, 35);
    Triangle triangle1 = new Triangle(20, 10);
    Square square2 = new Square(9);

    // I know that I can display the information this way
    // but I'd like to create a method to do this

    labelDisplayRectangle.Text = "Width: " + rectangle1.Width + " Height: " + rectangle1.Height + " Area: " + rectangle1.ComputeArea();
    labelDisplaySquare.Text = "Width: " + square1.Width + " Height: " + square1.Height + " Area: " + square1.ComputeArea();
    labelDisplayTriangle.Text = "Width: " + triangle1.Width + " Height: " + triangle1.Height + " Area " + triangle1.ComputeArea();
    labelDisplaySquare.Text = " Side: " + square2.Width + " Side: " + square2.Height + " Area: " + square2.ComputeArea();

    // I want to print my object rectangle1 with the format located in Display.

    Display(rectangle1);
    Display(square1);
    Display(square2);
    Display(triangle1);
}

// How do I set up this method to do that?

public void Display()
{
    labelDisplayRectangle.Text = "Width: " + width + " Height: " + height + " Area: " + area; 
}

Upvotes: 0

Views: 68

Answers (1)

Selman Genç
Selman Genç

Reputation: 101701

I assume all your classes inheriting from a common base class (for ex: Shape) or implements an interface.If so you can define your method like this:

public void Display(Shape shape, Label lbl)
{
    lbl.Text = string.Format("Width:  {0} Height: {1} Area: {2}",
                                shape.Width,shape.Height, shape.ComputeArea());
}

And you can call it like this:

Display(rectangle,labelDisplayRectangle);
Display(square1,labelDisplaySquare);
Display(triangle1,labelDisplayTriangle);

Also if you override ToString method for your base class, it would be easier.Then you just need to call ToString method on your Shape instance to get string representation of your Shape.

Upvotes: 1

Related Questions