1

Just trying to confirm my understanding of a colon in a method. I found this post which explains that the code after the colon is run before the called method.

Does this mean with the code below that Shape is run before Circle? And Circle is run before Cylinder?

public abstract class Shape
{
    public const double pi = Math.PI;
    protected double x, y;

    public Shape(double x, double y) => (this.x, this.y) = (x, y);
    public abstract double Area();
}
public class Circle : Shape
{
    public Circle(double radius) : base(radius, 0) { }
    public override double Area() => pi * x * x;
}
public class Cylinder : Circle
{
    public Cylinder(double radius, double height) : base(radius) => y = height;
    public override double Area() => (2 * base.Area()) + (2 * pi * x * y);
}
public class TestShapes
{
    private static void Main()
    {
        double radius = 2.5;
        double height = 3.0;

        Circle ring = new Circle(radius);
        Cylinder tube = new Cylinder(radius, height);

        Console.WriteLine("Area of the circle = {0:F2}", ring.Area());
        Console.WriteLine("Area of the cylinder = {0:F2}", tube.Area());

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
Area of the circle = 19.63
Area of the cylinder = 86.39
*/
dbc
  • 104,963
  • 20
  • 228
  • 340

2 Answers2

2

For constructors (function names with the same name as the class name), the : indicates that a constructor of the base class will be called and will execute first, with any passed parameters, before the code of the child constructor.

So for the function public Cylinder(double radius, double height) : base(radius) the constructor for Circle is executed before the code in the Cylinder constructor, which in turn calls the constructor for Shape setting this.x and this.y, and then executes its own code, which it has none, and then finally the code in Cylinder constructor is executed, setting y.

Matt Brand
  • 346
  • 1
  • 4
  • 17
1

You are right. When you create an instance of Cylinder, the constructor of Shape is executed first, initialising x and y. Then the constructor of Circle is executed, initialising radius. Finally, the constructor of Cylinder is executed, changing y to height.

Note that this : base syntax only works on constructor. It doesn't work on ordinary methods. For ordinary methods, you do this:

public void Method1() {
    base.Method1(); // to call the base class implementation first
}

And this pattern of calling the base class constructor before anything else makes sense, doesn't it? Each subclass is a specialisation of their direct superclasses. So it makes sense to first "construct" the superclass, then "construct" the more specialised subclass.

Sweeper
  • 213,210
  • 22
  • 193
  • 313