Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Lazy<T> be preferred to lazy initialization in a getter?

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?

like image 800
w128 Avatar asked Mar 06 '15 15:03

w128


1 Answers

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

like image 151
Patrick Hofman Avatar answered Nov 03 '22 01:11

Patrick Hofman