C# – Is it true I should not do “long running” things in a property accessor


And if so, why?
and what constitutes "long running"?

Doing magic in a property accessor seems like my prerogative as a class designer. I always thought that is why the designers of C# put those things in there – so I could do what I want.

Of course it's good practice to minimize surprises for users of a class, and so embedding truly long running things – eg, a 10-minute monte carlo analysis – in a method makes sense.

But suppose a prop accessor requires a db read. I already have the db connection open. Would db access code be "acceptable", within the normal expectations, in a property accessor?

Best Solution

Like you mentioned, it's a surprise for the user of the class. People are used to being able to do things like this with properties (contrived example follows:)

foreach (var item in bunchOfItems)
    foreach (var slot in someCollection)
        slot.Value = item.Value;

This looks very natural, but if item.Value actually is hitting the database every time you access it, it would be a minor disaster, and should be written in a fashion equivalent to this:

foreach (var item in bunchOfItems)
   var temp = item.Value;
   foreach (var slot in someCollection)
      slot.Value = temp;

Please help steer people using your code away from hidden dangers like this, and put slow things in methods so people know that they're slow.

There are some exceptions, of course. Lazy-loading is fine as long as the lazy load isn't going to take some insanely long amount of time, and sometimes making things properties is really useful for reflection- and data-binding-related reasons, so maybe you'll want to bend this rule. But there's not much sense in violating the convention and violating people's expectations without some specific reason for doing so.