Search code examples
c#standards

Should read-only calculated properties be methods?


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 there a C# standard for this?

public class WorkOrder
{
    public int LaborHours { get; set; }
    public decimal LaborRate { get; set; }

    // Should this be LaborCost()?
    public decimal LaborCost
    {
        get
        {
            return LaborHours * LaborRate;
        }
    }
}

Solution

  • It's OK to use calculated properties rather than methods, as long as the calculation doesn't take a noticeable time

    See Property usage guidelines

    Excerpt from the section on properties vs methods:

    Use a property when the member is a logical data member.

    Use a method when:

    • The operation is a conversion, such as Object.ToString.

    • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.

    • Obtaining a property value using the get accessor would have an observable side effect.

    • Calling the member twice in succession produces different results.

    • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.

    • The member is static but returns a value that can be changed.

    • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.