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

Viewed 2508

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.

1 Answers
Related