Initialize class fields in constructor or at declaration?

前端 未结 15 2149
南旧
南旧 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条回答
  •  梦毁少年i
    2020-11-22 02:13

    Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:

    • Fields in static classes/methods
    • Fields typed as static/final/et al

    I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.

提交回复
热议问题