tags:

views:

73

answers:

4

Possible Duplicate:
C# member variable initialization; best practice?

In C#, is it better to initialise a variable at the time of declaration, or within a constructor?

eg.

public Foo{
   Bar b = new Bar();
   public Foo() { }
}

OR

public Foo{
    Bar b;
    public Foo() { b = new Bar(); }
}
+2  A: 

In a simple class like this it won't make any difference. The advantage of the first is that you could omit the constructor declaration entirely.

Mark Byers
I don't think the example given was a specific implementation.
dr_tchock
@dr_tchock: How can you be so sure? Maybe he works in a FooBar factory? ;)
Mark Byers
A: 

I simply don't like initializing instance members at the time of declaration, apart from constants. It is just hurting my eyes, especially if the class names are long. Otherwise from a language aspect, it isn't much of a difference.

Petar Minchev
Including local variables? I try to initialize local variables at the point of declaration as much as reasonably possible. I find it makes the meaning of the variable clearer.
Jon Skeet
@Jon Not including local variables:) I think the author was asking for class members, not local variables:) At least this was my impression.
Petar Minchev
Jon: In all fairness, Petar did specify instance members.
Gabe
@Gabe I edited my answer to be more clear what I mean. But John posted before that:)
Petar Minchev
@Petar: Okay, that makes more sense - thanks for editing.
Jon Skeet
+3  A: 

Well, "better" depends on the situation.

It's worth knowing that it does end up making a difference in some obscure cases... because the base class constructor gets run after variable initializers, but before the constructor body. That can make a difference in the (nasty) case where a virtual method is called from the base constructor. It's worth avoiding that situation to start with where possible, mind you :)

I think if the initial value never depends on any parameters, it makes sense to initialize it at the point of declaration... but I wouldn't claim to be entirely consistent in applying that myself :)

Jon Skeet
A: 

It all depends, of course, but I just like to put the initializers where they make the most sense. Sometimes it's good to put them with their member declarations; other times it's good to put them in the constructor.

If I have multiple constructors, though, I prefer to put the initalizers with the declaration, so as to avoid the same initializer code in multiple places -- particularly for readonly fields.

Gabe