Last active
July 23, 2017 15:54
-
-
Save wgross/9687a6b1459925e454a5166fc70c7353 to your computer and use it in GitHub Desktop.
Most simple lazy implementation. (Contains a Linqad Main methods for verification)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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