Search code examples
c#asp.netobject-initialization

What is the difference in how these objects are instantiated?


What is the difference between the two cases below:

class Data
{
    PersonDataContext persons = new PersonDataContext();
    public Data() {}
}

versus

class Data
{
    PersonDataContext persons;
    public Data() 
    {
        persons = new PersonDataContext();
    }
}

I have the same question in asp.net:

public partial class Data : System.Web.UI.Page
{
    PersonDataContext persons = new PersonDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

versus

public partial class Data : System.Web.UI.Page
{
    PersonDataContext persons;
    protected void Page_Load(object sender, EventArgs e)
    {
        persons = new PersonDataContext();
    }
}

Solution

  • Field initializers runs before the constructor call. So In Case 1 your object of PersonDataContext will be created before the constructor call.

    PersonDataContext persons = new PersonDataContext();
    

    In 2nd case, your constructor will execute first and then it will 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 your Main method

    static void Main(string[] args)
    {
    
        Data d1 = new Data();
        Data2 d2 = new Data2();
        Console.Read();
    }
    

    Output

    In PersonDataContext Constructor // Case 1

    In Data Contructor //Case 1

    In Data2 Constructor //Case 2

    In PersonDataContext Constructor // Case 2


    For the asp example, In first case your Field is initialized before the Page_Load event, and in 2nd case your Field is initialized in the Page_Load event