Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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"/"this" constructor.</p> <p>The constructor approach can be used with auto-implemented properties (field initializers cannot) - i.e.</p> <pre><code>[DefaultValue("")] public string Foo {get;set;} public Bar() { // ctor Foo = ""; } </code></pre> <p>Other than that, I tend to prefer the field initializer syntax; I find it keeps things localized - i.e.</p> <pre><code>private readonly List&lt;SomeClass&gt; items = new List&lt;SomeClass&gt;(); public List&lt;SomeClass&gt; Items {get {return items;}} </code></pre> <p>I don't have to go hunting up and down to find where it is assigned...</p> <p>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:</p> <pre><code>public Bar() : this("") {} public Bar(string foo) {Foo = foo;} </code></pre> <p>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 <code>base(...)</code> - i.e. the <code>public Bar(string foo)</code> ctor. The other constructor does <em>not</em> run field initializers, since it knows they are done by the <code>this(...)</code> ctor.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload