Jo Smo Jo Smo - 16 days ago 6
C# Question

The use of base in inheritance context

Could someone please explain to me why the result here is: DVD Unknown DVD:DVD

using System;

class Program
{
class M
{
internal string n;

internal M() { }
internal M(string N)
{
Console.Write(N + " ");
n = N;
}
}

class D : M
{
internal D(string N) : base(N) { n = "DVD:" + N; }
}

static void Main(string[] args)
{
M d1 = new D("DVD");

M m1 = new M("Unknown");

Console.WriteLine(" " + d1.n);

}
}


I understand most parts of the code, except for this line:

internal D(string N) : base(N) { n = "DVD:" + N; }


I know that base calls something from the parent class, but in this case i just don't get it. :/

Answer

Let's break apart this line:

internal D(string N) : base(N)
{
    n = "DVD:" + N;
}

The part you're most likely needing clarification on is base(N). base(N) is a call to the M(string N) constructor. This happens before the body of this constructor (n = "DVD...) is run.

I think the code will be clearer if you modify what is printed slightly:

class M
{
    internal string n;

    internal M() { }
    internal M(string N)
    {
        Console.WriteLine("in base " + N);
        n = N;
    }
}

class D : M
{
    internal D(string N) : base(N) { n = "DVD:" + N; }
}

static void Main(string[] args)
{
    M d1 = new D("DVD");

    M m1 = new M("Unknown");

    Console.WriteLine("d1.n is " + d1.n);
}

Outputs

in base DVD
in base Unknown
d1.n is DVD:DVD

The same thing is happening in your output of DVD Unknown DVD:DVD, just all on one line: first, D's constructor calls M's constructor, which writes DVD (this happens before DVD: is added to it). Then, M's constructor is called directly, which writes Unknown. Then, you write d1's n, which is DVD:DVD.