Search code examples
c#.net.net-core.net-6.0lazy-initialization

Lazy tag is not working as supposed to be - Lazy is not lazy - initialized before used / called


I am intending to use lazy initialization with a .NET core 6 WPF application with the following.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    Lazy<List<int>> myNumbersList = new Lazy<List<int>>(Enumerable.Range(1, 99999999)
    .Select(x => x).ToList());

    List<int> myNumbersList2 = new List<int>(Enumerable.Range(1, 99999999)
    .Select(x => x).ToList());
}

enter image description here

enter image description here

They are both initialized even before the constructor of the WPF's MainWindow is called.

Isn't lazy supposed to be initialized whenever it is used?


Solution

  • You are using Lazy ctor which accepts preinitialized value:

    Lazy<T>(T)
    Initializes a new instance of the Lazy class that uses a preinitialized specified value.
    Parameters
    value T
    The preinitialized value to be used.

    You are probably looking for one accepting Func<T> value factory:

    Lazy<T>(Func<T>)
    Initializes a new instance of the Lazy<T> class. When lazy initialization occurs, the specified initialization function is used.
    Parameters
    valueFactory Func<T>
    The delegate that is invoked to produce the lazily initialized value when it is needed.

    Lazy<List<int>> myNumbersList = new Lazy<List<int>>(() => Enumerable.Range(1, 99999999)
       .Select(x => x).ToList());