Search code examples
c#constructorthisprogram-entry-pointradix

What happens if you have :base() in the top class?


I am having problems understanding what happens if you put the :base() in top class. The code goes like this...

class A {
 public A(): this(3) {
  Console.Write("1");
 }
 public A(int x): base() {
  Console.Write("{0}", x);
 }
}

class B:A {
 public B(): this(4) {
Console.Write("3");
 }
 public B(int x) {
  Console.Write("{0}", x):
 }
}

class C:B {
 public C(int x): base() {
  Console.Write("{0}", x):
 }
 public C(): this(7) {
  Console.Write("6");
 }
}

class Program {
 public static void Main(string[] args) {
   C c = new C();
  }

I don't get why we need to start from the top (class A). So what would be the output?


Solution

  • Your top classes inherit implicitly from System.Object (C# alias object). So this basically calls the default constructor of object. But since the default constructor of the base class is called by default anyway, this doesn't change anything.

    So

    public A(int x)
        : base()
    {
    }
    

    and

    public A(int x)
    {
    }
    

    are equivalent.

    If a base class constructor has parameters, then you must call it explicitly to pass the required parameters.

    See: Using Constructors (C# Programming Guide)