Base class field initialization in derived class

1) If I define a field in a base class like

myType myField = new MyField();

Will this field be always initialized in a derived class?

2) If I initialize this field through base class default (parameterless) constructor will it be initialized in a derived class?

Assuming I do not call any :base() constructors from derived type.

My point is to instantiate field with default value only in base class and provide overridden initialization in derived classes.

Jon Skeet
people
quotationmark

Yes, fields will always be initialized. If you don't explicitly chain to any other constructors, you'll chain to base() implicitly. You'll always end up chaining right up the type hierarchy until you hit Object.

My point is to instantiate property with default value only in base class and provide overridden initialization in derived classes.

Then I suggest in the base class, you have two constructors, one of them possibly protected:

public class BaseClass
{
    private MyType myField;

    protected BaseClass(MyType myField)
    {
        this.myField = myField;
    }

    public BaseClass() : this(new MyType())
    {
    }
}

Then constructors from your derived types can chain to either constructor, as appropriate... and you don't end up creating an instance of MyType when you don't need to.

people

See more on this question at Stackoverflow