The order of C# object initialization is:
- Derived static fields
- Derived static constructor
- Derived instance fields
- Base static fields
- Base static constructor
- Base instance fields
- Base instance constructor
- Derived instance constructor
In this example, your question involves 3, 6, 7, 8, corresponding to your order of 3, 4, 5, 6.
There is a more detailed code example in this link, to prevent this link from being unavailable one day in the future, I will extract it here.
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Console.ReadLine();
}
}
class Base
{
public Base()
{
Console.WriteLine("Base.Instance.Constructor");
this.m_Field3 = new Tracker("Base.Instance.Field3");
this.Virtual();
}
private Tracker m_Field1 = new Tracker("Base.Instance.Field1");
private Tracker m_Field2 = new Tracker("Base.Instance.Field2");
private Tracker m_Field3;
static private Tracker s_Field1 = new Tracker("Base.Static.Field1");
static private Tracker s_Field2 = new Tracker("Base.Static.Field2");
virtual public void Virtual()
{
Console.WriteLine("Base.Instance.Virtual");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived.Instance.Constructor");
this.m_Field3 = new Tracker("Derived.Instance.Field3");
}
private Tracker m_Field1 = new Tracker("Derived.Instance.Field1");
private Tracker m_Field2 = new Tracker("Derived.Instance.Field2");
private Tracker m_Field3;
static private Tracker s_Field1 = new Tracker("Derived.Static.Field1");
static private Tracker s_Field2 = new Tracker("Derived.Static.Field2");
override public void Virtual()
{
Console.WriteLine("Derived.Instance.Virtual");
}
}
class Tracker
{
public Tracker(string text)
{
Console.WriteLine(text);
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.