Lab: Computed Properties#


In this lab, we will delve into the practical usage of computed properties. We aim to understand how computed properties can make our code more concise and maintainable by encapsulating calculations within property accessors.

Provided Code#

Carefully review the provided code. Notice how the Rectangle class has two public properties, called Width and Height, with both get and set accessors.

class Rectangle
    public double Width { get; set; }
    public double Height { get; set; }


Step 1: Introduce a property called Area with a get accessor#

First, let’s add a computed property to the Rectangle class called Area. Define a read-only property Area that computes the area as the product of Width and Height.

Instantiate a Rectangle object, assign values to Width and Height, and use Console.WriteLine to print the area.

Rectangle rect = new Rectangle { Width = 4, Height = 5 };

Step 2: Add a set accessor to Area#

Now, add a set accessor to the Area property. For simplicity, when the area is set, adjust the Width and Height such that the rectangle becomes a square with the given area. Implement the setter inside the Area property.

Test the setter by setting the Area property of the Rectangle object and then print the Width, Height, and Area to check that they all updated correctly.

Rectangle rect = new Rectangle { Width = 10, Height = 8 };

rect.Area = 25;

Console.WriteLine($"{rect.Width} x {rect.Height} = {rect.Area}");
5 x 5 = 25

🤔 Reflection

When setting the Area we’re assuming that the Rectangle is a square. Are there other sensible assumptions we could have made when implementing this set accessor?

Step 3: Add a property called Perimeter#

Now we will enhance our Rectangle class further by adding another computed property named Perimeter. The get accessor should calculate the perimeter of the rectangle based on its Width and Height, while the set accessor should set the Width and Height based on the given perimeter.

Instantiate a Rectangle object, set its Width and Height, and use Console.WriteLine to print out the Perimeter.

Rectangle rect = new Rectangle { Width = 4, Height = 5 };

rect.Perimeter = 100;

Console.WriteLine($"{rect.Width} + {rect.Width} + {rect.Height} + {rect.Height} = {rect.Perimeter}");
25 + 25 + 25 + 25 = 100

🤔 Reflection

How does this property enhance the usability and functionality of the Rectangle class?