Initialize class fields in constructor or at declaration?

前端 未结 15 2400
南旧
南旧 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:58

    There is a slight performance benefit to setting the value in the declaration. If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor).

提交回复
热议问题