Lazy <T> False load error: field initializer cannot reference non-static fields, method or property

I am trying to use lazy loading for the first time to initialize a progress object in my class. However, I get the following error:

A field initializer cannot reference non-static fields, a method, or a 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 modern 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.

+8
generics c # lazy-loading
source share
1 answer

This initializer requires that this be passed to the capture class, and this not available from the field initializer. However, it is available in the 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 would use only get accessor, p

+20
source share

All Articles