A good part of an hour wasted! I looked at your example here:
http://www.bartdesmet.net/images/CQuizFieldinitializationcontd_B5D2/image0_thumb4.png
After erecting a lot of scaffolding, and beating my head against the
wall, and thinking I've gone crazy, I've concluded that this program
does not appear to work as expected due to an optical illusion that
has something to do with the way "ToString()" is implimented for base
classes. Or so it seems.
Anyway, a great example of how these virtual table type languages do
stuff behind the scenes that are counterintutive.
Below is my dissected version of your example.
I'd like to know your interpretation of what your program does.
RL
class Foo
{
private int i=69;
public Foo ()
{
i = 99;
Console.WriteLine("!{0}", ToString()); //same as below
// Console.WriteLine("!{0}", this.ToString());
}
public Foo(int eye)
{
i = eye;
Console.WriteLine("!Foo base loves explicit initialization
outside of constructor always! {0}", this.ToString());
}
}
class Bar1 : Foo
{
private int i=321; //overrides the normal constructor always
(at least for ToString)
// private int i; // gives zero, i=123; never called
public Bar1() //public Bar1 ():base() //same thing, not what
you think
{
i = 123;
}
public Bar1(int k): base(k) //still not called, ever!
(for .ToString)
{
Console.WriteLine("Bar1's i is: {0}", k);
i = k;
}
public override string ToString()
{
return ("Hi" + i.ToString()); //
}
}
class Bar2 : Foo
{
// private int i=1234; //overrides constructor always
private int i; //try this now: gives zero, not 10001, always,
even with parametized constructor k
public Bar2 ()
{
i = 10001; //makes no difference
}
public Bar2(int k) :base(k) //i = k still not called, ever!
[for .ToString()]
{
i = k;
}
public int get_i()
{
int eye = i;
return eye;
}
public override string ToString()
{
return ("Hi!!" + i.ToString()); //
}
}
////////////////////////////////
/*
// in static void Main(string[] args) ---
Bar1 bar1 = new Bar1(432); //doesn't do what you think
Bar2 bar2 = new Bar2(201); //""
Console.WriteLine("Bar2 int i is: {0}", bar2.get_i());
*/
/* OUTPUT
!Foo base loves explicit initialization outside of constructor always!
Hi321
Bar1's i is: 432
!Foo base loves explicit initialization outside of constructor always!
Hi!!0
Bar2 int i is: 201
Press any key to continue . . .
*/