C# member variable initialization; best practice?

In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any “base”https://stackoverflow.com/”this” constructor.

The constructor approach can be used with auto-implemented properties (field initializers cannot) – i.e.

[DefaultValue("")]
public string Foo {get;set;}
public Bar() { // ctor
  Foo = "";
}

Other than that, I tend to prefer the field initializer syntax; I find it keeps things localized – i.e.

private readonly List<SomeClass> items = new List<SomeClass>();
public List<SomeClass> Items {get {return items;}}

I don’t have to go hunting up and down to find where it is assigned…

The obvious exception is where you need to perform complex logic or deal with constructor parameters – in which case constructor-based initialization is the way to go. Likewise, if you have multiple constructors, it would be preferable for the fields to always get set the same way – so you might have ctors like:

public Bar() : this("") {}
public Bar(string foo) {Foo = foo;}

edit: as a side comment, note that in the above, if there are other fields (not shown) with field initializers, then they are only directly initialized in the constructors that call base(...) – i.e. the public Bar(string foo) ctor. The other constructor does not run field initializers, since it knows they are done by the this(...) ctor.

Leave a Comment