Initialize class fields in constructor or at declaration?

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

    Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"

    Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.

    In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.

    So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.

提交回复
热议问题