I have a object with properties that are expensive to compute, so they are only calculated on first access and then cached.
private List notes;
If the value is non-trivial to compute, I generally prefer using a method (GetNotes()
). There's nothing stopping you from caching the value with a method, plus you can add the [Pure] attribute (.NET 4) if applicable to indicate the method does not alter the state of the object.
If you do decide to stay with the following, I recommend:
Whenever you have a lazily-evaluated property, you should add the following attribute to ensure that running in the debugger behaves the same as running outside of it:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Also, starting with .NET 4, you can use the following:
// the actual assignment will go in the constructor.
private readonly Lazy> _notes = new Lazy>(CalcNotes);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public List Notes
{
get { return _notes.Value; }
}