constructors are executed in the order from top to bottom I.E. base\'s first followed by derived one. This arangement is based on an important OOP assurance that an object (
Field initialisers are executed in the constructor, and as the constructor in the base class is called first, all field initialisers are also executed before the derived constructor executes.
Example:
public class Base {
// field initialiser:
private string _firstName = "Arthur";
public string FirstName { get { return _firstName;}}
public string LastName { get; private set; }
// initialiser in base constructor:
public Base() {
LastName = "Dent";
}
}
public class Derived : Base {
public string FirstNameCopy { get; private set; }
public string LastNameCopy { get; private set; }
public Derived() {
// get values from base class:
FirstNameCopy = FirstName;
LastNameCopy = LastName;
}
}
Test:
Derived x = new Derived();
Console.WriteLine(x.FirstNameCopy);
Console.WriteLine(x.LastNameCopy);
Output:
Arthur
Dent