Consider the following contrived program:
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
var stuff = myClass.MyProperty; // this takes 5 seconds
var stuff2 = myClass.MyProperty; // this is effectively instantaneous
}
}
class MyClass
{
private Lazy<IEnumerable<string>> _myProperty =
new Lazy<IEnumerable<string>>(MyService.TimeConsumingLoadOperation);
public IEnumerable<string> MyProperty
{
get { return _myProperty.Value; }
}
}
class MyService
{
public static IEnumerable<string> TimeConsumingLoadOperation()
{
Thread.Sleep(5000);
return new List<string>();
}
}
Drawing from part of CA1024:
Properties should behave as if they are fields; if the method cannot, it should not be changed to a property.
This makes a lot of sense to me. I wouldn't expect that accessing property could result in a noticeable delay, and the code above would be clearer if MyProperty
was retrieved in a method call instead. To that end, are there situations where lazy loading a property (as opposed to using a method) would be appropriate?