Should properties in C# perform a lot of work?

However, now that C# gave the world Properties, it seems silly to use getter and setter methods instead.

Before thinking about how expensive properties should be, I would advise you to think about whether the concept you are modeling is best represented as a "property of something". Properties exist in the language to express attribution of other entities - if SomeValue is not logically a property of the type it belongs to, then you should consider using getter/setter methods instead.

Should properties in C# perform a lot of work?

Having said that, it helps to make properties inexpensive when possible. Most developers expect properties to be efficient wrappers around some internal state of the type they belong to. Violating this expectation makes it harder for developers to write well performing code that uses the property. For example, if a property is used in as a condition of a for loop it will be evaluated on each iteration - if it's expensive ... well that can be bad.

Properties are also often accessed in the debugger - you don't want properties to perform expensive logic as this can inhibit debugging. Property getters that perform operations with side effects (like querying a database, for example) are generally a bad practice as well, because they can introduce heisenbugs when inspecting the behavior of an application in the debugger.

What is the alternative.

You may also want to read up on this answer which provides some good general guidelines for property design. I would also advise you to read Choosing Between Properties and Methods in the .NET design guidelines on MSDN.

Sometimes it makes sense to create a property which is read-only (no setter) but where one or more separate methods exist that set the internal state related to that property. Whether to use this idiom depends on whether the operations on your object are exposed semantically as "changing state" or "performing activity". When it's the latter, I tend to use methods (rather than property setters) to express this behavior.


The general rule of thumb is properties should not be expensive to call. If they are expensive to call, make them into a getter instead. This can't always be followed, you definitely need to use judgment.


The exact amount of too much work is debatable. The best answer is that properties should rather perform less work than more work :)

One thing that Get Properties should never do is to change the state of the object.

Tags:

C#

Properties