Properties vs Methods

后端 未结 16 1900
傲寒
傲寒 2020-11-22 08:23

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?

We are busy having this debate and have found some areas where it

16条回答
  •  萌比男神i
    2020-11-22 08:50

    Yes, if all you're doing is getting and setting, use a property.

    If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.

    In the middle is a grey area where the line can be a little blurred. There is no hard and fast rule and different people will sometimes disagree whether something should be a property or a method. The important thing is just to be (relatively) consistent with how you do it (or how your team does it).

    They are largely interchangeable but a property signals to the user that the implementation is relatively "simple". Oh and the syntax is a little cleaner.

    Generally speaking, my philosophy is that if you start writing a method name that begins with get or set and takes zero or one parameter (respectively) then it's a prime candidate for a property.

提交回复
热议问题