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());
}
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?
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
valueT
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 theLazy<T>
class. When lazy initialization occurs, the specified initialization function is used.
Parameters
valueFactoryFunc<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());