Field initializers are started before the constructor is called . So, in case 1, your PersonDataContext object will be created before the constructor is called.
PersonDataContext persons = new PersonDataContext();
In the second case, your constructor will execute first and then initialize the field.
You can do a simple test
class PersonDataContext { public PersonDataContext() { Console.WriteLine("In PersonDataContext Constructor"); } } class Data { PersonDataContext persons = new PersonDataContext(); public Data() { Console.WriteLine("In Data Contructor"); } } class Data2 { PersonDataContext persons; public Data2() { Console.WriteLine("In Data2 Constructor"); persons = new PersonDataContext(); } }
and then in the main method
static void Main(string[] args) { Data d1 = new Data(); Data2 d2 = new Data2(); Console.Read(); }
Exit
In the constructor of PersonDataContext // Case 1
In Data Contructor // Case 1
In the constructor of Data2 // Case 2
In the constructor of PersonDataContext // Case 2
For an example asp. In the first case, your field is initialized before the Page_Load event, and in the second case, your field is initialized in the Page_Load event
Habib source share