Skip to content

Lazy Initialization

Question

Describe Lazy<T>.

Short interview answer

Lazy<T> delays creation of a value until its Value property is first accessed. It is useful when construction is expensive or may never be needed.

Detailed answer

Lazy<T> stores a factory and does not call it until Value is requested. For example, new Lazy<Regex>(() => new Regex(pattern)) avoids constructing a costly regular expression during application startup if a user might never open the feature that needs it. Once Value is requested, the result is retained and returned on later requests.

Decide whether multiple threads can reach Value at the same time and choose the documented thread-safety mode accordingly. Lazy initialization trades startup work for first-use latency and moves constructor failures to the first caller. It is a good fit for optional expensive state, not a default replacement for simple eager construction.

Sources