Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Creating Lazy Objects

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

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

Normally with a Lazy 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?

like image 919
maxp Avatar asked Oct 04 '13 10:10

maxp


People also ask

What is lazy initialization of objects?

Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

How do you initialize a Lazy?

Implementing a Lazy-Initialized Property To implement a public property by using lazy initialization, define the backing field of the property as a Lazy<T>, and return the Value property from the get accessor of the property. The Value property is read-only; therefore, the property that exposes it has no set accessor.

What is a Lazy instance?

Lazy initialization is a technique that defers the creation of an object until the first time it is needed. In other words, initialization of the object happens only on demand. Note that the terms lazy initialization and lazy instantiation mean the same thing—they can be used interchangeably.

Is lazy initialization a design pattern?

Abstract. The lazy initialization pattern embodies the just-in-time philosophy of data delivery. It delays the construction of values or data structures until that data is actually needed. Lazy initialization is a popular design pattern in both Java and Objective-C.


2 Answers

To get the list of all the lazily initialized values:

var created = items.Select(c => c.Value).ToList();
like image 82
Ahmed KRAIEM Avatar answered Oct 06 '22 21:10

Ahmed KRAIEM


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.)

like image 34
Guffa Avatar answered Oct 06 '22 21:10

Guffa