Search code examples
c#lazy-loadinglazy-initialization

Force creating Lazy<T> objects


I'm being given a collection of Lazy<T> items. I then want to forcibly 'create' them all in one go.

void Test(IEnumerable<Lazy<MailMessage>> items){
}

Normally with a Lazy<T> item, the contained object won't be created until one of it's member's is accessed.

Seeing as there is no ForceCreate() method (or similar), I am forced to do the following:

var createdItems = items
    .Where(a => a.Value != null && a.Value.ToString() != null)
    .Select(a => a.Value);

Which is using ToString() to force created each item.

Is there a neater way to forcibly create all items?


Solution

  • You need two things to create all the lazy items, you need to enumerate all items (but not necessarily keep them), and you need to use the Value property to cause the item to be created.

    items.All(x => x.Value != null);
    

    The All method needs to look at all values to determine the result, so that will cause all items to be enumerated (whatever the actual type of the collection might be), and using the Value property on each item will cause it to create its object. (The != null part is just to make a value that the All method is comfortable with.)