Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 581
Tuyen Avatar asked Nov 15 '12 12:11

Tuyen


1 Answers

In the first case you initialize the variable at the site of declaration.

In the second, you initialize it in a constructor.

The main difference is that if you have additional constructors and either forget to initialize or chain the constructors, you can have an uninitialized variable.

like image 52
Oded Avatar answered Oct 08 '22 07:10

Oded