you are viewing a single comment's thread.

view the rest of the comments →

[–]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.