Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy<T> Lazy loading error : A field initializer cannot reference the non-static field, method, or property

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.

like image 695
bobbo Avatar asked Aug 06 '12 12:08

bobbo


1 Answers

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

like image 90
Marc Gravell Avatar answered Oct 29 '22 14:10

Marc Gravell