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:
using System;
class Base
{
public Base()
{
Console.WriteLine(ToString());
}
}
class Derived : Base
{
private int x = 5;
private int y;
public Derived()
{
y = 5;
}
public override string ToString()
{
return string.Format("x={0}, y={1}", x, y);
}
}
class Test
{
static void Main()
{
// Prints x=5, y=0
new Derived();
}
}
I'm not aware of any subtle differences. I usually like to put all initialization in the constructor, because I think it makes the code more readable. But that's more of a style choice and personal preference. I haven't heard of a technical reason to justify it one way or the other. I doubt that there's any performance impact.
Constants that are static and final are a different matter. I initialize those in-line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With