Is there any benefit to doing the following:
public class Foo
{
private Bar bar;
public Foo()
{
bar = new Bar();
}
}
Instead of doing it like so:
public class Foo
{
private Bar bar = new Bar();
public Foo()
{
}
}
Given that at instantiation, the private member variable in either example will be instantiated, I don’t believe there is a difference, but I’ve seen it enough times to where I’m curious.
In the exact case you’ve given, there isn’t a difference – but in general there is.
Variable initializers are executed before the base class constructor is called. If that base constructor calls a virtual method which uses some of the instance variables, you can see that difference.
For spec fans, it’s in section 10.11.2 of the C# 4 spec:
Here’s an example demonstrating this:
Result:
Now having said the above, I would try hard to avoid calling virtual methods from a constructor. You’re basically asking the derived class to work in a partially-initialized fashion. However, it’s a difference you should be aware of.
As for where to initialize variables… I have to admit I’m not particularly consistent, and I don’t find that’s actually a problem. If I have any specific bias, it’s probably to initialize anything which won’t depend on any parameters at the point of declaration, leaving the variables which I can’t initialize without extra information to the constructor.