I am trying to wrap my head around whether this is possible. My hunch is that it is not but wanted to confirm.
The following higher order function uses the null coalescing operator:
public static Func<T> Coalesce<T>(this Func<T> source)
where T : class
{
T local = default(T);
return delegate
{
return local ?? (local = source());
};
}
The goal is to use it inside a property like so:
protected string SomeMember
{
get { return Coalesce(() => GetSomeMember())(); }
}
If it worked as intended, the GetSomeMember() function would only be called once the first time the property is called. Thereafter the stored instance of the property can be returned. (its basic memoization / null coalescing concept).
Now the tricky part comes in trying to trap the stored instance inside a closure instead of opting to use a private field. I know you could store the state of ‘SomeMember’ inside the class which contains SomeMember, but I am explicitly trying to avoid that just for curiosity’s sake. The goal would be for everything needed to remain inside the get { } block (that includes not storing the delegate returned from Coalesce()).
Since both the inner returned function and the outer function are called everytime the property is accessed, there is a problem. The ‘T local’ variable gets re-assigned every time, and thus the null coalescing operator always re-invokes GetSomeMember().
Thoughts?
It wouldn’t work like this, because you’re calling
Coalesce()(not a great name, BTW) every time you call the getter. You could save the delegate to a field and use that. But if you’re doing that, it’s much better to useLazy<T>from the framework: