Possible Duplicate:
Best Practice: Initialize class fields in constructor or at declaration?
Most of the time, I see the way of initializing a variable like this
public class Test
{
private int myIntToInitalize;
public Test()
{
myIntToInitalize = 10;
}
}
From my perspective, this is the most general way of initializing a variable. Most of the code in books, blogs and also internal implementations of .NET are equivalent to my example.
Recently I saw people doing the initialization directly, so without setting the value in the constructor.
public class Test
{
private int myIntToInitalize = 10;
}
In point of view, there is not difference whether initialize and declare a variable or initialize the variable in the constructor.
Apart from the best practices and the length of code lines, where are the benefits of initialize a variable directly and are there subtle differences?
There’s one potentially significant difference in some cases.
Instance initializers are executed before the base class constructor is executed. So if the base class constructor invokes any virtual methods which are overridden in the derived class, that method will see the difference. Usually this shouldn’t be a noticeable difference, however – as invoking virtual methods in a constructor is almost always a bad idea.
In terms of clarity, if you initialize the variable at the point of declaration, it makes it very clear that the value doesn’t depend on any constructor parameters. On the other hand, keeping all the initialization together helps readability too, IMO. I would try to make sure that wherever possible, if you have multiple constructors they all delegate to one “master” constructor which does all the “real” initialization – which means you’ll only put those assignments in one place either way.
Sample code to demonstrate the difference: