Read the syntax
Lazy<T> postpones construction until Value is first accessed and then reuses the result. Its default mode synchronizes initialization across threads. Use a .NET 8+ console project; replace Program.cs with this C# example.
Creating Lazy does not call the factory. Both Value reads share the object from the single successful initialization.
Syntax
new Lazy<T>(() => CreateValue()); lazy.ValueExamples
Lazy Initialization
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
int calls = 0;
var cache = new Lazy<string>(() => { calls++; return "ready"; });
Console.WriteLine(cache.IsValueCreated);
Console.WriteLine(cache.Value);
Console.WriteLine(cache.Value);
Console.WriteLine(calls);- Expected output: False ready ready 1
- Creating Lazy does not call the factory. Both Value reads share the object from the single successful initialization.
- Use lazy initialization only when deferring the cost is beneficial.
Best practices
- Use lazy initialization only when deferring the cost is beneficial.
- Understand exception caching and thread-safety mode before using factories with side effects.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference