Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created March 9, 2017 11:20
Show Gist options
  • Save mgravell/b547455bb4afe25cdae44d8cc78b8bdd to your computer and use it in GitHub Desktop.
Save mgravell/b547455bb4afe25cdae44d8cc78b8bdd to your computer and use it in GitHub Desktop.
// context: http://stackoverflow.com/questions/11828780/lazyt-lazy-loading-error-a-field-initializer-cannot-reference-the-non-static/11828838?noredirect=1#comment72503092_11828838
using System;
class Program
{
static void Main()
{
var obj = new MyType();
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"{i}: {obj.Value ?? "(null)"}");
}
}
}
class MyType
{
private readonly Lazy<string> _foo;
public string Value => _foo.Value;
public MyType()
{
_foo = new Lazy<string>(() =>
{
Console.WriteLine("Lazy invoked");
return null;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment