-1

So I'm having this class with its public property:

public static class DataStore 
{
    public static readonly List<Item> Items;
    static DataStore 
    { 
        Items = new List<Item> 
        {
            new Item {Name = "A"},
            new Item {Name = "B"},
            new Item {Name = "C"},
            ...//many more
        };
    }
}

To be memory-efficient, I'm adding a List<Lazy<Item>> to the DataStore:

List<Lazy<Item>> LazyItems = new List<Lazy<Item>> 
{
    new Lazy<Item>(() => new Item {Name="A"}),
    new Lazy<Item>(() => new Item {Name="B"}),


};

However List<Item> is a public property and being referenced in plenty places. How can I keep the existing List<Item> and make use of the new property ?

Dio Phung
  • 5,944
  • 5
  • 37
  • 55
  • 1
    This change is *increasing* the memory footprint, not decreasing it. – Servy Oct 10 '16 at 18:48
  • 1
    Have you bothered profiling this in the first place to actually determine if the memory consumption in your original example is a bottleneck? – David L Oct 10 '16 at 18:48
  • There's not enough context here to help you. Taken literally, the only valid answer is "you can't do that". There's also not enough information in your question to know whether what you're trying to do is even useful. But assuming it is in your real-world scenario, you'd have to at a minimum change `List Items` to `IList Items`, so that you can provide a custom `IList` implementation that knows about the `LazyItems` object and can retrieve elements from there. Consider also using `IReadOnlyList`, since presumably it doesn't make sense to modify either list. – Peter Duniho Oct 10 '16 at 19:24
  • This is very good example of why `static`/global variables are bad practice. – Fabio Oct 10 '16 at 20:12

1 Answers1

1

You can't. A List<Item> needs to have a fully materialized list of already created items, therefore, to have one you need to have already created all of the items. You can't create some, but not all, of the items while still treating it as a List<Item>.

Servy
  • 202,030
  • 26
  • 332
  • 449