I have a C# record like the following, with a property that is expensive to compute:
sealed record MyAwesomeRecord(Dictionary<int, int> SomeDictionary)
{
public int ExpensiveToComputeProperty => SomeDictionary.Sum(e => e.Value);
//...
}
var original = new MyAwesomeRecord( new() { [0] = 0 });
var modified = original with { SomeDictionary = new() { [1] = 1 } };
Instead of re-computing the ExpensiveToComputeProperty value on every access, I would like to compute it only once, after "construction". But apparently with C# records, the constructor is not invoked again after modification with with. I tried the following ways to fix this:
- Use a regular
classinstead, but that way I can no longer use thewithsyntax, which I'd like to keep using. - Store the
ExpensiveToComputePropertyin a regular property or field. This does not work, because it is initialized once, but not after changingSomeDictionarywithwith. - AFAIK, there are plans to introduce nice syntax that would let me keep this property updated in C# 10. Unfortunately, C# 10 is not here yet.
Is there a way to use records that avoids re-doing the expensive computation?