c# - The use of base in inheritance context -
could please explain me why 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 parts of code, except line:
internal d(string n) : base(n) { n = "dvd:" + n; }
i know base calls parent class, in case don't it. :/
let's break apart line:
internal d(string n) : base(n) { n = "dvd:" + n; }
the part you're needing clarification on base(n)
. base(n)
call m(string n)
constructor. happens before body of constructor (n = "dvd...
) run.
i think code clearer if modify 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 " + d1.n); }
outputs
in base dvd in base unknown d1.n dvd:dvd
the same thing happening in output of dvd unknown dvd:dvd
, on 1 line: first, d
's constructor calls m
's constructor, writes dvd
(this happens before dvd:
added it). then, m
's constructor called directly, writes unknown
. then, write d1
's n
, dvd:dvd
.
Comments
Post a Comment