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?
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.
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.
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.
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.
To get the list of all the lazily initialized values:
var created = items.Select(c => c.Value).ToList();
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With