Skip to content

Instantly share code, notes, and snippets.

@wgross
Last active July 23, 2017 15:54
Show Gist options
  • Save wgross/9687a6b1459925e454a5166fc70c7353 to your computer and use it in GitHub Desktop.
Save wgross/9687a6b1459925e454a5166fc70c7353 to your computer and use it in GitHub Desktop.
Most simple lazy implementation. (Contains a Linqad Main methods for verification)
void Main()
{
var lazy = new SimpleLazy<string>(() =>
{
"calculating".Dump();
return "hello";
});
lazy.Value.Dump("1");
lazy.Value.Dump("2");
var lazy2 = new SimpleLazy<int>(null);
}
// Define other methods and classes here
public sealed class SimpleLazy<T>
{
private readonly Func<T> calculateValue;
private bool isCalculated = false;
private T value;
public SimpleLazy(Func<T> calculateValue)
{
this.calculateValue = calculateValue ?? throw new ArgumentNullException(nameof(calculateValue));
}
public T Value => this.isCalculated ? this.value : this.Calculate();
private T Calculate()
{
this.value = this.calculateValue();
this.isCalculated = true;
return this.value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment