Jo Smo
Jo Smo

Reputation: 7169

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. :/

Upvotes: 0

Views: 166

Answers (2)

Tim S.
Tim S.

Reputation: 56536

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.

Upvotes: 2

Bura Chuhadar
Bura Chuhadar

Reputation: 3751

First of all, Console.WriteLine(" " + d1.n); will give you DVD:DVD because base means use the parent class' constructor. So, when you send your parameters into your D class, it is sending your code to your M class, it is executing it which gives you "DVD" on your screen and then it is changing the value of n. After that you are sending the "Unknown" value your M class directly which is not related with your D class anymore and it is showing you "Unknown" on your screen. At the end you are requesting D class' n value which is already "DVD". So the result is DVD Unknown DVD:DVD. I hope this makes sense for you.

Upvotes: 1

Related Questions