63

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;
        }
    }
}
5
  • 6
    You have it perfectly correct. The only thing I would add is this. before LaborHours and LaborRate, but that's just for readability. Commented Jan 8, 2010 at 20:54
  • 24
    And personally I would not add this. since my preference is that it reduces readability... :-)
    – Cellfish
    Commented Jan 8, 2010 at 21:07
  • 1
    @Cellfish: Agreed, let's try to cut down on the amount of unnecessary verbosity please. Commented Aug 29, 2011 at 3:26
  • 1
    Worth noting that the 'this' keyword improves readability in some cases, for example when fields are not prefixed with underscores (a personal dislike of mine) and you want to distinguish between fields and private variables. Commented Apr 24, 2014 at 14:06
  • 6
    Don't forget that properties can be used for binding purposes while methods cannot Commented Dec 7, 2015 at 12:00

11 Answers 11

64

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

3
  • I'm glad to hear this isn't bad practice. I quite like it after coming from Java land. Thanks for the link! Commented Jan 8, 2010 at 23:20
  • is it fine if a DTO object has some property that returns result of a service (cache for example, some sort of lazy loading)?
    – shkiper
    Commented Mar 2, 2017 at 12:32
  • 3
    @shkiper, well, it's probably a matter of opinion, but I don't think a DTO should call a service. It should be a purely "dumb" object that does nothing but hold data. Commented Mar 2, 2017 at 13:02
15

I think methods should perform actions on the object, typically change the state of the object. Properties should reflect the current state of the object even if the property is calculated. So you should keep your properties IMO.

7
  • What if the operation involves significant amount of computation? Commented Jan 8, 2010 at 20:53
  • 10
    Programmers assume property access is constant-time, so Microsoft suggests not to do any complex computation in properties, but instead to use methods when there is significant processing involved. Commented Jan 8, 2010 at 20:55
  • 1
    Doesn't matter. Whether it's a property or method doesn't tell the caller anything. Commented Jan 8, 2010 at 20:55
  • 1
    Another case is when a would-be property would return a new mutable instance which is not tied to the object on which a property is called. E.g. if you do return new int[] { ... }, then it really should be a method. If you return the same array all the time, then property is okay. Commented Jan 8, 2010 at 20:56
  • 1
    If you return the same instance on repeated calls to (lazily loaded) property, then there's no problem with being a property according to rule above. And if it returns different instances, then it's not really lazily loaded, is it :) Commented Jan 8, 2010 at 23:09
7

I think they should all be properties. As long as it doesn't change the state of the object, I'm cool with it as a property.

Additionally, if I'm using your class for data binding (WPF, etc.), then I can bind directly to your property without having to modify/extend the class.

1
  • 2
    Agree, though it's important to remember that if you want to bind to the computed property, then the other relevant property setters or mutator methods need to raise the PropertyChanged event for the computed property.
    – itowlson
    Commented Jan 8, 2010 at 21:06
3

If they are a) lightweight and b) have no side effects, I would make them Properties.

Lightweight is a bit fuzzy of course, but the rule of thumb is: If I ever have to worry calling a Property (be it in a loop or anywhere else), it should possibly be a method.

2
  • 1
    You could also have a lazy property that can be either forced to recalculate based on some explicit method [such as Refesh()] or implicit event [such as timeout or dirty cache]. This would allow properties for easy binding/serialization and the ability to keep data up-to-date. Commented Jan 8, 2010 at 21:11
  • Very True. Lazy-Loading Properties are rare, but useful. Commented Jan 8, 2010 at 21:24
1

I would leave them as properties. But there's not "standard" reason to do things one way or another. If you're by yourself, do whatever you like best. If you're on a team, then follow conventions the rest of your team are following.

1

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.

0

In my opinion, it's a preference; it's what you want to do. I do propreties in most cases, unless there is logic involved. Additionally, if you need to pass in parameters to change the functionality then obviously a method would apply...

0

Depends, if your "properties" become mammoths and require a whole slew of business logic they shouldn't be properties, there should be a method. The example you posted looks ok to be a property. No standard way of doing it, go with your gut instinct; if it looks like it needs to do a lot you probably need a method.

0

It's largely just syntactic sugar anyway, so do want you is convention in your team, or what you prefer, as long as it is just returning information about the object and not changing it or interacting with other objects.

0

MSDN gives information about this here

Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data.

Which one do you think it is? An action calculate/getLaborCost or data?

WorkOrder workOrder = new WorkOrder();
workOrder.LaborHours = 8;
workOrder.LaborRate = 20;

decimal cost = workOrder.LaborCost; // This is OK here

but if you are going to do this for the same object also:

worOrder.LaborHours = 18;
decimal newCost = workOrder.LaborCost 

Now this cannot be a property. It would be a lot better to be a method.

0

Sometimes, you have to consider also what you're modeling... On some domains, the calculated values are often or expected to be an attribute of the model -- a Property. If this were the case, then write it as a Property even though the calculation is not at all trivial or a little bit expensive to compute. Just document it on your API or implement some caching mechanism to minimize recomputation for this property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.