Codectionary / Developer documentation / C#

Lazy Initialization

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.

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

Examples

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);
  1. Expected output: False ready ready 1
  2. Creating Lazy does not call the factory. Both Value reads share the object from the single successful initialization.
  3. 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

Specifications & further reading