Initialize class fields in constructor or at declaration?

前端 未结 15 2115
南旧
南旧 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 02:14

    I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to "initialize at declaration" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is "base" and another is the newly declared ones, and it cost me quite some time to debug.

    The lesson: to initialize inherited fields, you'd do it inside of the constructor.

提交回复
热议问题