0

Imaginge this class

Class Person
{
  public string Name { get; set; }
  public int SomeExpensiveCalculation {
    get {
      return TimeConsumingCalulation(Name )
    }
  }
}



Since get is a method, I assume, when the the property "SomeExpensiveCalculation" is never requested or used, the function "TimeConsumingCalulation" is never executed. Is this correct?

Zoidbergseasharp
  • 3,697
  • 1
  • 11
  • 20
  • 5
    _"Is this correct?"_ Yes. But I'd say this is bad practice, a property should not be a long running calculation (that probably even might throw exceptions). The worse point than never calling it is that `TimeConsumingCalculation()` will be called _every_ time you access the property.. – René Vogt Jul 24 '19 at 14:42
  • Call the method directly, instead of hiding it in a property. All that property does is make it so that you don't have to put parentheses on the end of the call. – Robert Harvey Jul 24 '19 at 14:42
  • Take a look at [this](https://stackoverflow.com/questions/23102639/are-c-sharp-properties-actually-methods). `get` is a method. A method isn't executed until you call it. As Rene said, however, using a property vs a method communicates to the caller that they're just retrieving a value, not invoking some long-running method. If it's a property someone is likely to reference it again and again, not realizing that they're calling a long-running method. If it's a method they'll store the result in a variable. Another way to tell - set a breakpoint. – Scott Hannen Jul 24 '19 at 14:43
  • That will be fun when you debug and add a watch on that object – Franck Jul 24 '19 at 14:48
  • 1
    Take a look at the Lazy generic class. It allows you to evaluate your expensive function only once, and only when the value is requested. – Steve Todd Jul 24 '19 at 14:54

2 Answers2

2

That's correct. Property getter is just a method that executes when called.

But properties should be simple, avoid expensive calculations inside the property get.

Miroslav Zadravec
  • 3,510
  • 5
  • 24
  • 35
0

That is correct. Properties are just Syntax Sugar for GetValue and SetValue function pairs. I think they also had some added reflection support.

With Time Consuming Operation for a value that may not be needed, maybe a Lazy[T] would be a good tool? It might at least be clearer that Lazy Initialsiation is your intention. Between it and WeakRefrence[T], you can usually cover edge cases with Memory allocation or time consumption.

However wich code is actually executed at runtime is a bit tricky. .NET has this Feature called a "just in time" compiler, and it may or may not do all kinds of Optimsiations. It can add a temporary variable to avoid retrieving the same collection value twice. Or cut unused temporary variables. Cut out a large part of the bounds checks in a array accessor.

Inling properties is way up there, but usually this will not affect any working of it.

Christopher
  • 9,634
  • 2
  • 17
  • 31