Implementation & tests
Implement Rectangle, Circle, and Triangle; add basic input guards; write tiny ad-hoc tests without a framework.
Implementation plan
Goal: Implement shapes and verify them.
- Implement Rectangle, Circle, Triangle
- Guard invalid inputs
- Add a tiny Assert helper
- Run quick checks in Main
Rectangle & Circle
Add simple guards in constructors so dimensions are positive. Keep formulas small and clear.
using System;
public interface IShape
{
double Area();
double Perimeter();
}
public sealed class Rectangle : IShape
{
private readonly double _w, _h;
public Rectangle(double w, double h)
{
if (w <= 0 || h <= 0) throw new ArgumentOutOfRangeException("w/h must be > 0");
_w = w; _h = h;
}
public double Area() { return _w * _h; }
public double Perimeter() { return 2 * (_w + _h); }
}
public sealed class Circle : IShape
{
private readonly double _r;
public Circle(double r)
{
if (r <= 0) throw new ArgumentOutOfRangeException("r must be > 0");
_r = r;
}
public double Area() { return 3.14159 * _r * _r; }
public double Perimeter() { return 2 * 3.14159 * _r; }
}
public class Program
{
public static void Main(string[] args)
{
IShape a = new Rectangle(3, 4);
IShape b = new Circle(2);
Console.WriteLine("Rect A=" + a.Area() + " P=" + a.Perimeter());
Console.WriteLine("Circ A=" + b.Area() + " P=" + b.Perimeter());
}
}
All lessons in this course
- Design (interfaces + inheritance)
- Implementation & tests
- Polymorphic behaviors