Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static void Main()
- {
- try
- {
- List<Shape> shapes = new List<Shape>();
- shapes.Add(new Triangle(5, 3));
- shapes.Add(new Circle(4, 4));
- shapes.Add(new Rectangle(10, 4));
- //Polymorphism
- foreach (Shape item in shapes)
- {
- Console.WriteLine(string.Format("Surface : {0} -> {1}",item.GetType(),item.CalculateSurface()));
- }
- }
- catch (ArgumentException err)
- {
- Console.WriteLine(err.Message);
- }
- }
- public abstract class Shape
- {
- //fields
- private double width;
- private double height;
- //properties
- public double Width
- {
- get { return this.width; }
- private set
- {
- if (value <= 0)
- {
- throw new ArgumentException("Value must be positive!");
- }
- this.width = value;
- }
- }
- public double Height
- {
- get { return this.height; }
- private set
- {
- if (value <= 0)
- {
- throw new ArgumentException("Value must be positive!");
- }
- this.height = value;
- }
- }
- //abstract method
- public abstract double CalculateSurface();
- //constructor
- protected Shape(double width, double height)
- {
- this.Width = width;
- this.Height = height;
- }
- }
- public class Triangle : Shape
- {
- public override double CalculateSurface()
- {
- return this.Height * this.Width / 2d;
- }
- public Triangle(double width, double height) : base(width,height)
- {
- }
- }
- public class Rectangle : Shape
- {
- public override double CalculateSurface()
- {
- return this.Height * this.Width;
- }
- public Rectangle(double width, double height)
- : base(width, height)
- {
- }
- }
- public class Circle : Shape
- {
- public override double CalculateSurface()
- {
- double radius = this.Width / 2d;
- return Math.PI * radius * radius;
- }
- public Circle(double width, double height)
- : base(width, height)
- {
- if (width != height)
- {
- throw new ArgumentException("In circle width must be equal to height!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment