Home > database >  Lazy property initialization not working in C#
Lazy property initialization not working in C#

Time:09-25

I'm having trouble initializing properties within a class using the method described in this documentation.

Sample:

public class MyClass
{
    private Lazy<string> _lazyString;

    public MyClass()
    {
        _lazyString = new Lazy<string>(() => "hello world");
    }

    public string MyString => _lazyString.Value;
}

When I debug I can see that _lazyString has its boolean IsCreated set to true before I've even accessed the MyString property. Has something changed in the recent c# iterations?

My target framework is netcoreapp3.1

CodePudding user response:

Works as expected.

The problem with testing this with the debugger, as pointed out by @Progman, is that by hovering the value you trigger the lazy operation.

To really test the laziness in this case you can use the Lazy.IsValueCreated property.

You can see with the following code

static void Main(string[] args)
{

    MyClass c = new MyClass();
    Console.WriteLine($"MyString not yet called.");
    Console.WriteLine($"Is value created? {c.IsValueCreated}");
    var s = c.MyString;
    Console.WriteLine($"MyString called.");
    Console.WriteLine($"Is value created? {c.IsValueCreated}");
}

public class MyClass
{
    private Lazy<string> _lazyString;

    public MyClass()
    {
        _lazyString = new Lazy<string>(() => "hello world");
    }

    public string MyString => _lazyString.Value;

    public bool IsValueCreated => _lazyString.IsValueCreated;

}

Output:

MyString not yet called. 
Is value created? False 
MyString called. 
Is value created? True
  • Related