Initialize class fields in constructor or at declaration?

前端 未结 15 2315
南旧
南旧 2020-11-22 01:16

I\'ve been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:



        
15条回答
  •  独厮守ぢ
    2020-11-22 01:55

    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.

提交回复
热议问题