0

I am trying to understand some code for my programming exam and I've stumbled upon this notation that I can't seem to find the explanation for. I've searched stackoverflow, msdn and several online tutorials, but no luck.

The code is something like this:

class A
{
    public A(): this("b")
    {
        Console.WriteLine("c"); 
    }

    public A(string i)
    { 
        Console.WriteLine(i); 
    }
}

class B : A
{
    public B()
    { 
        Console.WriteLine("a"); 
    }
    ---------------
    static void Main(string[] args)
    { 
        A b = new A(); 
    }
}

This, supposedly, prints out "bc", but I can't even understand the inheritance and all. I can't find out what is this notation here does:

public A(): this("b")
{
     Console.WriteLine("c"); 
}

The only thing I found that looked remotely similar are object initializers, but only in one online tutorial. Checked MSDN for them - no similar code. Anyone able to help? Thanks in advance!

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
dzenesiz
  • 1,388
  • 4
  • 27
  • 58
  • 2
    Did you read the specification section on constructor syntax? – Eric Lippert Sep 07 '15 at 15:03
  • 4
    [It's called `"Constructor Chaining"`.](http://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it) – Matthew Watson Sep 07 '15 at 15:04
  • What 'notation' in particularly is confusing to you? `:this("b")` will call the class A parameterized constructor and simply prints "b" and then the A parameterless constructor is called - printing "c". – Marcus Sep 07 '15 at 15:05

1 Answers1

2

This has nothing to do with object-initializers. Its about constructor-chaining. When any method (including constructors as well) has such a this(...) what you say is as very first call that overload with the similar signatur, so in your case this("b") will first call this ctor: public A(string i). After this call has been done the actual work within that particular constructor is done, in your excample Console.WriteLine("c");.

Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • If I've understood this correctly, the order of calling would be: superclass constructor, chained supercass constructor, subclass constructor. But what if I had a matching constructor in a subclass, but none in the superclass? In the given example, if I had public B("M") {} and called it in Main()? – dzenesiz Sep 08 '15 at 10:21
  • You have to provide any sort of construrtor-chaining, be it implicitly or explicitely. In your case as you already have a base-class-constructor with matching signature (`public A(string)`) that one would be called before your ctor for class `B`. If class `A` hadn´t such a ctor a compiler-error would be generated. This chaining ensures that every derived object is fully initialized including all of its base-members. – MakePeaceGreatAgain Sep 08 '15 at 12:17