Why should I avoid using Properties in C#?

后端 未结 14 545
渐次进展
渐次进展 2020-12-22 18:05

In his excellent book, CLR Via C#, Jeffrey Richter said that he doesn\'t like properties, and recommends not to use them. He gave some reason, but I don\'t really understand

14条回答
  •  天命终不由人
    2020-12-22 18:24

    I don't agree with Jeffrey Richter, but I can guess why he doesn't like properties (I haven't read his book).

    Even though, properties are just like methods (implementation-wise), as a user of a class, I expect that its properties behave "more or less" like a public field, e.g:

    • there's no time-consuming operation going on inside the property getter/setter
    • the property getter has no side effects (calling it multiple times, does not change the result)

    Unfortunately, I have seen properties which did not behave that way. But the problem are not the properties themselves, but the people who implemented them. So it just requires some education.

提交回复
热议问题