C# read-only calculated properties, should they be methods?

前端 未结 11 1192
刺人心
刺人心 2021-01-31 13:55

I have several entities that have calculated fields on them such as TotalCost. Right now I have them all as properties but I\'m wondering if they should actually be methods. Is

11条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 14:29

    If a property is particularly expensive to calculate, I might change it to a GetWhatever() method. This serves as a hint to whoever uses my class that this value requires some significant work to arrive at, and the caller should cache the value rather than calling the method multiple times.

    Trivial calculations are perfectly appropriate inside of properties.

提交回复
热议问题