I have a POCO class that is mostly built through a service. I hit the service with some info, get back a dto and use that to build parts of the object. What I’m trying to do is lazy load some of the bigger properties so that they’re only filled on demand. I thought this was the way to do it:
private List<User> _directReports;
public List<User>DirectReports
{
get
{
if (this._directReports == null)
{
SetDirectReports();
}
return this._directReports;
}
private set
{
this._directReports = value;
}
}
private void SetDirectReports()
{
using (var client = new ADSClient())
{
this._directReports = client.GetDirectReports(this.Guid);
}
}
Here’s the problem, and maybe I’m chasing ghosts, but when I step through debugger and look at the guts of the object after instantiating it, those fields have information in it, and it shouldn’t at that stage and completely defeats the purpose of what I’m trying to do. So I’m trying to understand this, am I doing this wrong? Is the compiler running the get method as some point that I’m not thinking about?
This is a debugger artifact. When you use a watch or a quick inspect to look at the property, the debugger will run the property getter so it can display its value. Which causes your lazy init code to execute. So you’ll never see the property return null.
Something to keep in mind.