Which object initialization style is more appropriate in C#?
-
Declare private object and initialize it in the same line:
private List<ReportRow> rows = new List<ReportRow>(); -
Declare private object and initialize it in the constructor:
private List<ReportRow> rows;In constructor
rows = new List<ReportRow>(); -
Declare private object and initialize it in the method where it is used:
private List<ReportRow> rows;and in my Run() method
rows = new List<ReportRow>();
Thanks
All of them are appropriate. It really depends on the details of the code. If you’re simply initializing the field to an empty list my preference is to initialize it in-line with the declaration. If you’re putting values into a list dependent on constructor parameters then I go with initializing it in the constructor. If the population is expensive and possible to skip then I’d go with initializing it the first time the consuming code is called.