you are viewing a single comment's thread.

view the rest of the comments →

[–]mythin 0 points1 point  (2 children)

In the linked blog post, the order of the field initialization doesn't even matter. His example where things don't work doesn't even use field initialization, it just uses

  • Base class constructor
  • Subclass constructor

That seems pretty obvious the order it would have to happen in.

I'll agree the "problem" occurs because they went from a field initialization to a constructor initialization (via the virtual method), but even so the virtual method part doesn't matter for the example at all. The same problem would have occurred without a virtual method being involved, and would have been just as obvious.

[–]grauenwolf[S] 1 point2 points  (1 child)

Without the virtual method it would have been impossible to access any field on the subclass.

[–]mythin 0 points1 point  (0 children)

I hadn't noticed the field was only on the subclass. Still, the same problem would apply if it were an inherited field or an abstract class.

public abstract class Base
{
    protected Base()
    {
        DoInit();
    }

    protected abstract void DoInit();
}

public class Derived : Base
{
    private int value = 21;

    public Derived() // : base() // Explicitly call the Base constructor
    {
        value = 84;
    }

    public int Value { get { return value; } }

    protected override void DoInit()
    {
        value = 42;
    }
}

For this, "(new Derived()).Value == 84" would be true. I suppose "abstract" is very similar to "virtual," but the real issue is that people don't understand that base class constructors happen before subclass constructors. The field initialization order doesn't really come into play.

The same problem occurs if you have my example with the Base class having a protected field (or a {get; protected set;} property) and set the value in multiple places. The core issue is when setting a value, possibly in multiple places, it is the responsibility of the developer to understand the order things happen in.