Start learning free

LESSON 251 OF 572 · FUNCTIONS & CLASSES

Rectangle Class in C#: Fields, Constructor and Methods

Practice O(1) Read the full explanation

A class bundles some values with the questions you can ask about them. Write a class Rectangle that remembers a rectangle's width and height, and can tell its area, its perimeter, and whether it is a square.

Implement the class Rectangle:

  • Rectangle(width, height) creates a rectangle with the given sizes.
  • area() returns the area of the rectangle: its width times its height.
  • perimeter() returns the perimeter: the length all the way around, twice the width plus twice the height.
  • isSquare() returns true if the width and the height are equal, and false otherwise.

Each line of the input is one rectangle: its width and its height. The test code first creates a Rectangle for every line, then asks each of them, in order, for its area, its perimeter and whether it is a square, and prints the three answers on one line, the boolean as True or False. So each object must keep its own sizes. The starter code spells these names the way your language does (in Go and Rust, Rectangle is a struct with methods).

 

Example 1:

Input:
    Rectangle(3, 4)
Output: 12 14 False
Explanation: The area is 3 · 4 = 12. Going around, the sides are 3 + 4 + 3 + 4 = 14.
The width and the height differ, so it isn't a square.

Example 2:

Input:
    Rectangle(5, 5)
Output: 25 20 True
Explanation: 5 · 5 = 25, and 4 sides of 5 make 20. Both sizes are 5: a square is a rectangle with equal sides.

Example 3:

Input:
    Rectangle(2, 10)
    Rectangle(10, 2)
Output:
20 24 False
20 24 False
Explanation: Two objects, each with its own sizes. Turning a rectangle on its side changes neither its area nor its perimeter.

 

Constraints:

  • 1 <= width, height <= 104
  • At most 10 rectangles per test.

Note:

Each method needs only the two sizes, so each one runs in O(1) time.

STEP 1 OF 5
    Ctrl + Enter to check

    C# · FUNCTIONS & CLASSES

    Rectangle Class in C#, explained

    Problem overview

    A class bundles values with the questions you can ask about them. Rectangle remembers a width and a height, and answers three questions: its Area, its Perimeter and whether it IsSquare. Each object keeps its own sizes, so two rectangles never interfere with each other.

    For a 3 by 4 rectangle the area is 3 * 4 = 12, the perimeter is 3 + 4 + 3 + 4 = 14, and it is not a square. For 5 by 5 the area is 25, the perimeter 20, and it is a square.

    Approach

    Each question needs only the two sizes, so the class stores them once and every method works from them. That makes each method O(1): a multiplication, an addition or a comparison, whatever the sizes are.

    Two parts of a class matter here. Fields are the variables each object carries. The constructor has the same name as the class, no return type, and runs when you write new Rectangle(3, 4). Its job is to copy the parameters into the fields.

    Step by step

    1. Declare the fields. Two public int fields, width and height, one line each. Every object gets its own copy.
    2. Store the parameters. The constructor's parameters have the same names as the fields, so inside it width means the parameter and this.width means the field of the object being created.
    3. Area: return width * height. Inside a method, plain width is the field of the object the method was called on.
    4. Perimeter: return 2 * (width + height). The parentheses make the addition happen before the multiplication.
    5. IsSquare: return width == height. A comparison is already a bool, so no if is needed.

    The solution in C#

    class Rectangle {
        public int width;
        public int height;
    
        public Rectangle(int width, int height) {
            this.width = width;
            this.height = height;
        }
    
        public int Area() {
            return width * height;
        }
    
        public int Perimeter() {
            return 2 * (width + height);
        }
    
        public bool IsSquare() {
            return width == height;
        }
    }
    

    Using it:

    var r = new Rectangle(3, 4);
    Console.WriteLine(r.Area() + " " + r.Perimeter() + " " + r.IsSquare());
    var q = new Rectangle(5, 5);
    Console.WriteLine(q.Area() + " " + q.Perimeter() + " " + q.IsSquare());
    r.width = 10;
    Console.WriteLine(r.Area() + " " + q.Area());
    

    This prints:

    12 14 False
    25 20 True
    40 25
    

    C# prints a bool as True or False when it is joined to a string; the lesson's tests print the answers the same way. The last two lines show that each object has its own sizes: changing r.width changes r.Area() and leaves q alone. Because the fields are public, any code can do that.

    Edge cases and common mistakes

    • Forgetting this. in the constructor. Writing width = width; assigns the parameter to itself and leaves the field at 0. The compiler warns about it, and every area would then be 0.
    • Perimeter without parentheses. 2 * width + height is not the perimeter. Use 2 * (width + height).
    • Squares. A square is a rectangle with equal sides, so Rectangle(5, 5).IsSquare() is true. A 2 by 10 and a 10 by 2 rectangle have the same area and perimeter (20 and 24) and neither is a square.
    • Method names. C# is case-sensitive, and the methods are Area, Perimeter and IsSquare with a capital first letter, as in the starter code.

    How the class works

    A class is a blueprint, and new Rectangle(3, 4) builds one object from it. The class says that every rectangle has a width and a height. Each object then holds its own two numbers. When you call r.Area(), the method runs on r, so width and height inside it are r's values. The same method called on another object uses that object's values.

    Notice that the methods take no parameters. The sizes were handed over once, in the constructor, and the object remembers them. This is the difference between a class and a plain function such as Area(width, height), which would need the sizes again on every call.

    The size limits are small: each side is at most 10,000, so the area is at most 100,000,000, and that fits in an int.

    Testing

    Try these rectangles and compare:

    • Rectangle(3, 4) gives area 12, perimeter 14, False.
    • Rectangle(5, 5) gives 25, 20, True.
    • Rectangle(2, 10) and Rectangle(10, 2) both give 20, 24, False: turning a rectangle on its side changes neither number.
    • Rectangle(1, 1) gives 1, 4, True.
    • Rectangle(10000, 10000) gives 100000000, 40000, True.

    Other ways to write it

    C# lets a method with a single return use the shorter expression-bodied form. These three methods behave exactly like the ones above, and for a 3 by 4 rectangle they give 12, 14 and False:

    public int Area() => width * height;
    public int Perimeter() => 2 * (width + height);
    public bool IsSquare() => width == height;
    

    The lesson's fields are public to keep the first class simple. Larger C# programs usually make fields private and expose them through properties, so that the class decides how its values can change. For a small class like this one, public fields are fine.

    One more detail: int arithmetic wraps silently on overflow, so a very large width and height would give a wrong area without any error. The lesson's limits keep every answer well inside the range of int.

    Key takeaways

    • Fields hold what each object remembers; methods answer questions about it.
    • The constructor copies its parameters into the fields, using this. when the names match.
    • A comparison such as width == height is already a bool.
    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free