From .NET 4 onwards, Lazy<T>
can be used to lazily initialize objects. Intuitively, lazy initialization can also be performed in a public property's getter to provide the same functionality to the caller. I wonder if Lazy<T>
offers any inherent advantage over the latter and should thus be preferred?
Personally, I feel that Lazy<>
can quickly reduce code readability, but perhaps I've just seen it misused. On a plus side, it ensures thread safety, but there are many .NET synchronization constructs that - perhaps I'm wrong - make it quite easy to achieve the same inside a getter.
What are some considerations to be aware of when choosing the best approach?
Lazy<>
can be useful since it inludes support for multithreading too, something you have to build yourself when creating your own 'lazy'.
For code that doesn't need multi-threading, this would be the best performing and readable code in my opinion (using the null-coalescing operator).
return variable ?? (variable = new ClassName());
Note that since this code isn't thread safe, you could end up calling new ClassName()
multiple times.
You should introduce lock
ing then, and the readability will decrease. If it is just for readability, Lazy<>
might be not that bad in that case.
Also, Lazy<>
prevents you to use the backing field in the case of cached properties.
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