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

Time:11-18

Here a simple example. .NET core 6 WPF app

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

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

        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

CodePudding user response:

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());
  • Related