Lazy Properties in .NET 1003/14/2026
In this post, I explore a couple of ways to create lazy properties in C# and .NET 10. What does a lazy property mean in the context of this post? It is an object instance property that gets initialized with a value the first time its getter is invoked. The getter of the property does not need to provide thread-safe initialization. Let's review a couple of solutions available before .NET 10:
All the examples below initialize a string property. The initializing method is static and extracted as a member of a separate class:
public class Shared { public static int _counter = 0; public static string Zeros() { Interlocked.Increment(ref _counter); return new string('0', _counter); } }
The Zeros() method returns a new string object containing a number of 0 characters. The number of 0 characters corresponds to the number of times the method has been executed.