Should Lazy <T> prefer lazy getter initialization?

Starting with .NET 4, Lazy<T> can be used to lazily initialize objects. Intuitively, lazy initialization can also be performed on the public getter property to provide the caller with the same functions. I wonder if Lazy<T> offers any inherent advantage over the latter, and therefore should be preferred?

Personally, I feel that Lazy<> can quickly reduce code readability, but maybe I just saw it incorrectly. On the plus side, it provides thread safety, but there are many .NET synchronization constructs that I might be wrong to do - it's pretty easy to achieve the same thing inside the receiver.

What are some considerations to consider when choosing the best approach?

+6
source share
1 answer

Lazy<> may be useful as it includes multithreading support, something that you need to create yourself when creating your β€œlazy” one.

For code that does not require multithreading, this would be the most efficient and readable code, in my opinion (using the operator with zero coalescing).

 return variable ?? (variable = new ClassName()); 

Note that since this code is not thread safe, you can end up calling new ClassName() several times.

Then you should enter lock ing and readability will decrease. If it's easy to read, Lazy<> might not be so bad in this case.

In addition, Lazy<> does not allow the use of a support field in the case of cached properties.

+7
source

Source: https://habr.com/ru/post/983429/


All Articles