Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Lazy<T>?

I found this article about Lazy: Laziness in C# 4.0 – Lazy

What is the best practice to have best performance using Lazy objects? Can someone point me to a practical use in a real application? In other words, when should I use it?

like image 727
danyolgiax Avatar asked Jul 27 '11 16:07

danyolgiax


People also ask

What is Lazy T?

This enables the Lazy<T> object to create a copy of the lazily initialized object on each of several threads if the threads call the Value property simultaneously. The Lazy<T> object ensures that all threads use the same instance of the lazily initialized object and discards the instances that are not used.

Should I use Lazy C#?

Using the Lazy<T> class in C# Although you can write your own custom code to implement lazy initialization, Microsoft recommends using the Lazy<T> class instead. The Lazy<T> class in the System namespace in C# was introduced as part of . Net Framework 4.0 to provide a thread-safe way to implement lazy initialization.

Is Lazy T thread-safe?

By default, Lazy<T> objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy<T> objects it creates are thread-safe.

What is lazy loading in C sharp?

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading objects unnecessarily.


1 Answers

You typically use it when you want to instantiate something the first time its actually used. This delays the cost of creating it till if/when it's needed instead of always incurring the cost.

Usually this is preferable when the object may or may not be used and the cost of constructing it is non-trivial.

like image 120
James Michael Hare Avatar answered Oct 02 '22 10:10

James Michael Hare