Search code examples
c#objectpropertiesinstantiation

In C#. If a property isn't used, is it's value still calculated?


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?


Solution

  • 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.