Konstruktory: prostokąt i łańcuch this(...)

Klasy i obiekty - Podstawy C# (csharp)

Klasa może mieć kilka konstruktorów (przeciążanie konstruktorów). Konstruktor bezparametrowy Rectangle() : this(1, 1) nie powtarza kodu, tylko wywołuje drugi konstruktor z wartościami domyślnymi. Konstruktor z parametrami sprawdza, czy wymiary są dodatnie. Metody CalculateArea i CalculatePerimeter liczą na danych obiektu.
using System;

class Rectangle
{
  private double width;
  private double height;

  public Rectangle() : this(1, 1)
  {
  }

  public Rectangle(double width, double height)
  {
    this.width = width > 0 ? width : 1;
    this.height = height > 0 ? height : 1;
  }

  public double CalculateArea()
  {
    return width * height;
  }

  public double CalculatePerimeter()
  {
    return 2 * (width + height);
  }

  public void Print()
  {
    Console.WriteLine($"Prostokąt {width} x {height}: pole {CalculateArea()}, obwód {CalculatePerimeter()}");
  }
}

class Program
{
  static void Main(string[] args)
  {
    new Rectangle().Print();
    new Rectangle(4, 2.5).Print();
    new Rectangle(-3, 2).Print();
  }
}

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.