I'm looking for a way to only populate a property's value if that property is accessed (i.e. since in many cases the property does not need to be fetched, and the cost of fetching it is expensive). For demonstration purposes I've replaced my fetch logic with code to simply return the current date/time; giving a simple way to see if the original result is cached, or the same code's been called multiple times.
I think I'm using Lazy
incorrectly as I'm getting different results each time I output When
:
void Main()
{
var d = new Demo();
Console.WriteLine(d.When);
Thread.Sleep(1000);
Console.WriteLine(d.When);
Thread.Sleep(1000);
Console.WriteLine(d.When);
Thread.Sleep(1000);
Console.WriteLine(d.When);
}
class Demo
{
public Demo(){}
Lazy<DateTime> when => new Lazy<DateTime>(() => DateTime.UtcNow);
public DateTime When
{
get
{
return when.Value;
}
}
}
In researching I found a similar question / answer: C# Lazy Loaded Automatic Properties
In case I was somehow misusing anonymous functions I tried:
static DateTime OnlyOnce()
{
return DateTime.UtcNow;
}
//...
Lazy<DateTime> when => new Lazy<DateTime>(OnlyOnce);
...but with the same effect.
I have got this working by doing the following:
class Demo
{
public Demo(){}
Nullable<DateTime> when;
public DateTime When
{
get
{
//return (when = when ?? DateTime.UtcNow) ?? DateTime.MinValue; //previous hack to switch from Nullable to DateTime
return (when = when ?? DateTime.UtcNow).Value //cleaner way to do this conversion
}
}
i.e. if when
is populated we assign it to itself and return that value; if not we assign DateTime.UtcNow
to when
and then return that.
However I feel I've come up with a hacky solution & have misunderstood something basic about how Lazy works / is supposed to be used... Can anyone inform me where I'm going wrong with Lazy / why I'm seeing a different value returned each time I make a call to that property in my original code?