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 this
to be passed into a capture-class, and this
is not available from a field-initializer. However, it is available in a constructor:
private readonly Lazy<Progress> m_progress;
public MyType()
{
m_progress = new Lazy<Progress>(() =>
{
long totalBytes = m_transferManager.TotalSize();
return new Progress(totalBytes);
});
}
Personally, I'd just use the get
accessor, though ;p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With