2

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(); }
}
Community
  • 1
  • 1
CJ7
  • 22,579
  • 65
  • 193
  • 321
  • Better for whatever reasons are important in C# programming. – CJ7 Aug 11 '10 at 07:45
  • I prefer to go with your latter version. I think it spells out in the most readable way at what time certain pieces of code is executed, and it easily lets me interact with the default behavior by specifying new constructors that may or may not invoke the parameterless constructor. Adding this as a comment as it doesn't attempt to answer which way is *better* – David Hedlund Aug 11 '10 at 07:47
  • Also: http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration – Mark Byers Aug 11 '10 at 08:05

4 Answers4

3

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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
  • 811,555
  • 193
  • 1,581
  • 1,452
0

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
  • 46,889
  • 11
  • 103
  • 119
0

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
  • 84,912
  • 12
  • 139
  • 238