Created
November 23, 2017 22:03
-
-
Save manisero/4ed53eceecd0079586d13271a42f610b to your computer and use it in GitHub Desktop.
Light, allocation-free (but not thread-safe) Lazy implementation.
This file contains 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
public static class LightLazy | |
{ | |
public static LightLazy<TItem> Create<TItem>(Func<TItem> itemConstructor) | |
where TItem : class | |
=> new LightLazy<TItem>(itemConstructor); | |
} | |
public struct LightLazy<TItem> | |
where TItem : class | |
{ | |
private readonly Func<TItem> _itemConstructor; | |
public LightLazy(Func<TItem> itemConstructor) | |
{ | |
_itemConstructor = itemConstructor; | |
ItemOrNull = null; | |
} | |
/// <summary>Does not construct the item.</summary> | |
public TItem ItemOrNull { get; private set; } | |
/// <summary>Constructs the item if not yet constructed.</summary> | |
public TItem Item => ItemOrNull ?? (ItemOrNull = _itemConstructor()); | |
public bool ItemConstructed => ItemOrNull != null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment