Reputation: 808
I am new on lazy loading, but I want to be able to fill my lazy loading objects after it was created too. Is it possible?
I am getting this error when I want to define a "Lazy loading list" as a normal list I created:
Cannot implicitly convert type: 'System.Collections.Generic.List' to 'System.Lazy>'
Here is the code:
List<Currency> currencyOfMids = new List<Currency>();
obj.Merchant.CurrencyOfMids = currencyOfMids;
I tried identifying my list as a Lazy list too, but this time I can't fill it with "Add" command:
foreach (ListItem currencyItem in selectedCurrencies)
currencyOfMids.Add(new Currency() { Code = currencyItem.Text, Id = int.Parse(currencyItem.Value) });
'Lazy>' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'Lazy>' could be found (are you missing a using directive or an assembly reference?)
Upvotes: 1
Views: 2258
Reputation: 39277
You can assign to a Lazy<T>
, passing it the code that will create the list lazily when needed:
obj.Merchant.currencyOfMids = new Lazy<List<Currency>>(
() => ... code to generate currencies ...
);
Now when you want the list you access currencyofMids.Value
and if it hasn't already been generated it will generate it.
Upvotes: 1
Reputation: 546
I think you are looking for the Lazy<T>.Value
property. The Value property is how you access the T object (in your case, a List<Currency>
. The Value is automatically initialized the first time that you access it (which is what makes it lazy). You can't assign to value, but you can loop through currencyOfMids
and add each value to obj.Merchant.CurrencyOfMids.Value
.
foreach (ListItem currencyItem in selectedCurrencies)
currencyOfMids.Value.Add(new Currency() { Code = currencyItem.Text, Id = int.Parse(currencyItem.Value) });
Upvotes: 1