C# member variable initialization; best practice?

2019-01-01 10:59发布

Is it better to initialize class member variables on declaration

private List<Thing> _things = new List<Thing>();
private int _arb = 99;

or in the default constructor?

private List<Thing> _things;
private int _arb;

public TheClass()
{
  _things = new List<Thing>();
  _arb = 99;
}

Is it simply a matter of style or are there performance trade-offs, one way or the other?

7条回答
ら面具成の殇う
2楼-- · 2019-01-01 11:36

Actually, field initializers as you demonstrate is a convenient shorthand. The compiler actually copies the initialization code into the beginning of each instance constructor that you define for your type.

This has two implications: first, any field initialization code is duplicated in each constructor and, second, any code you include in your constructors to initialize fields to specific values will in fact re-assign the fields.

So performance-wise, and with regards to compiled code size, you're better off moving field initializers into constructors.

On the other hand, the performance impact and code 'bloat' will usually be negligable, and the field initializer syntax has the important benefit of lessening the risk that you might forget to initialize some field in one of your constructors.

查看更多
登录 后发表回答