I am trying to use lazy loading for the first time to initialize a progress object in my class. However, I’m getting the following error:
A field initializer cannot reference the non-static field, method, or property.
private Lazy<Progress> m_progress = new Lazy<Progress>(() =>
{
long totalBytes = m_transferManager.TotalSize();
return new Progress(totalBytes);
});
In .NET 2.0, I can do the following, but I would prefer to use a more up to date approach:
private Progress m_progress;
private Progress Progress
{
get
{
if (m_progress == null)
{
long totalBytes = m_transferManager.TotalSize();
m_progress = new Progress(totalBytes);
}
return m_progress;
}
}
Can anyone help?
Many thanks.
That initializer would require
thisto be passed into a capture-class, andthisis not available from a field-initializer. However, it is available in a constructor:Personally, I’d just use the
getaccessor, though ;p