I have a object with properties that are expensive to compute, so they are only calculated on first access and then cached.
private List<Note> notes;
public List<Note> Notes
{
get
{
if (this.notes == null)
{
this.notes = CalcNotes();
}
return this.notes;
}
}
I wonder, is there a better way to do this? Is it somehow possible to create a Cached Property or something like that in C#?
Yes it is possible. The question is, how much you are winning by doing it - you still need the initialization code somewhere, so at most you will be saving the conditional expression.
A while ago I implemented a class to handle this. You can find the code posted in this question, where I ask whether it's a good idea. There are some interesting opinions in the answers, be sure to read them all before deciding to use it.
Edit:
A Lazy<T> class that does basically the same as my implementation that I link to above, has been added to the .NET 4 Framework; so you can use that if you are on .NET 4. See an example here: http://weblogs.asp.net/gunnarpeipman/archive/2009/05/19/net-framework-4-0-using-system-lazy-lt-t-gt.aspx