Initialize class fields in constructor or at declaration?
Solution 1:
My rules:
- Don't initialize with the default values in declaration (
null
,false
,0
,0.0
…). - Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
- If the value of the field changes because of a constructor parameter put the initialization in the constructors.
- Be consistent in your practice (the most important rule).
Solution 2:
In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there's a slight nuance to this that Jon Skeet explains in the comments below). If there is already a constructor then any initialisation "above" will be moved into the top of it.
In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.