Should I avoid exposing the Lazy<T> class in public API?

87 Views Asked by At

In a design of the public interface of a library, is it legitimate to return an instance of Lazy<T> in a property, if I want lazy initialization? Or is it better to always hide the usage of Lazy<T> by means of encapsulation or other techniques?

2

There are 2 best solutions below

0
On BEST ANSWER

For the following I'm assumim you mean a Lazy Property.

It depends on the purpose of your interface.

Is it an important detail that the consumer knows that it is lazy ? Or is it just a technical detail which should not change the behavior for the consumer.

It you only have a short delay which must not be handled by the consumer then i would tend to haide the Lazy and only expose T directly.

If the consumer should be aware and may adapt this behavior then i would expose the lazy .

But thiking on this I would in most cases rather expose a method which indicates that the code may have side effects or may take a while.

0
On

I don't see any reason to directly expose Lazy<T> in the signature. In my use cases, the laziness is an implementation detail.

Don't use this in a property if initialization is long running. In such cases, rather provide a method, considering returning Task<T>.