Practical 5 Exercise: Implementing Inheritance in C#
Objective: Create a C# WinForms application that demonstrates the concept of inheritance by
implementing a base class and derived classes for different shapes.
Task Description:
1. Create a Base Class Shape:
o The Shape class should have the following properties and methods:
▪ Properties:
▪ Color (string)
▪ Area (double, read-only)
▪ Methods:
▪ SetColor(string color): A method to set the color of the shape.
▪ CalculateArea(): An abstract method that must be overridden by
derived classes to calculate the area of the shape.
▪ GetShapeInfo(): A method that returns a string containing the
shape's color and area.
2. Create Derived Classes Rectangle and Circle:
o The Rectangle class should inherit from the Shape class and have additional
properties and methods:
▪ Properties:
▪ Width (double)
▪ Height (double)
▪ Methods:
▪ SetDimensions(double width, double height): A method to
set the dimensions of the rectangle.
▪ CalculateArea(): Override this method to calculate the area of
the rectangle.
▪ GetRectangleInfo(): A method that returns a string containing
the rectangle's color, width, height, and area.
o The Circle class should inherit from the Shape class and have an additional
property and method:
▪ Properties:
▪ Radius (double)
▪ Methods:
▪ SetRadius(double radius): A method to set the radius of the
circle.
▪ CalculateArea(): Override this method to calculate the area of
the circle.
▪ GetCircleInfo(): A method that returns a string containing the
circle's color, radius, and area.
3. Create a WinForms Application:
o Add two RadioButtons to the form, allowing the user to select whether they want
to create a Rectangle or a Circle.
o Add a TextBox for the user to input the color of the shape.
o If the user selects Rectangle:
▪ Add two TextBoxes for inputting the width and height.
o If the user selects Circle:
▪ Add one TextBox for inputting the radius.
o Add a Button that, when clicked, will:
▪ Create an instance of either the Rectangle or Circle class based on the
user's selection.
▪ Set the shape's color and dimensions (or radius).
▪ Calculate the area of the shape.
▪ Display the shape's information, including color and area, in a Label on
the form.
4. Test the Application:
o Run the application and test it by creating both rectangles and circles with
different dimensions and colors.
o Ensure that the shape's information, including the correct area, is displayed when
the button is clicked.
Marking Points:
1. Creating the Base Class Shape with appropriate properties and methods: 10 marks
2. Implementing the Derived Classes Rectangle and Circle with correct inheritance and
overridden methods: 20 marks
3. Designing the WinForms interface with correct controls for input and output: 10 marks
4. Correctly implementing the logic to create shapes and calculate/display their area: 10
marks
Total: 50 marks