Skip to content

1.4 Constructors

In this exercise, you add three constructors with the following signatures (this is called overloading):
- An all-args constructor: Circle(double radius, double centerX, double centerY, string color)
- A default constructor: Circle()
- A constructor with only the radius: Circle(double radius)

Use the following default values: radius = 1, centerX = 0, centerY = 0, and color = "white".

TIP: You can easily add constructors by choosing CTRL+. and selecting Generate Constructor.... Select the attributes you want to use in the constructor and Visual Studio will do the rest.

  1. Add the following code to your Circle class:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    public Circle(double radius, double centerX, double centerY, string color)
    {
        this.Radius = radius;
        this.CenterX = centerX;
        this.CenterY = centerY;
        this.Color = color;
    }
    
    public Circle(double radius)
    {
        this.Radius = radius;
        this.CenterX = 0;
        this.CenterY = 0;
        this.Color = "white";
    }
    
    public Circle()
    {
        this.Radius = 1;
        this.CenterX = 0;
        this.CenterY = 0;
        this.Color = "white";
    }
    
    • A constructor has no return value.
    • The constructor always has exactly the same name as the class.
    • There can be multiple constructors, as long as they have different signatures (overloading).
    • In the all-args constructor, the names radius, centerX, centerY, and color appear twice. Once as an attribute of the Circle class and once as a parameter of the constructor. To avoid confusion, C# has the this keyword. This refers to the class itself. this.Radius therefore refers to the attribute of the class. The code this.Radius = radius assigns the value passed as a parameter to the attribute.
  2. Modify the code in the Main method as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    Circle myAllArgsCircle = new Circle(3, 1, 4, "green");
    Console.WriteLine(myAllArgsCircle.CalculatePerimeter());
    Console.WriteLine(myAllArgsCircle.CalculateArea());
    
    Circle myDefaultCircle = new Circle();
    Console.WriteLine(myDefaultCircle.CalculatePerimeter());
    Console.WriteLine(myDefaultCircle.CalculateArea());
    
    Circle myRadiusCircle = new Circle(6);
    Console.WriteLine(myRadiusCircle.CalculatePerimeter());
    Console.WriteLine(myRadiusCircle.CalculateArea());
    
  3. Run your program. Your output will look like this:

    1
    2
    3
    4
    5
    6
    18.84955592153876
    28.274333882308138
    6.283185307179586
    3.141592653589793
    37.69911184307752
    113.09733552923255
    
  4. Try some other values and view the output.