Skip to content

Instantly share code, notes, and snippets.

@manisero
Created November 23, 2017 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manisero/4ed53eceecd0079586d13271a42f610b to your computer and use it in GitHub Desktop.
Save manisero/4ed53eceecd0079586d13271a42f610b to your computer and use it in GitHub Desktop.
Light, allocation-free (but not thread-safe) Lazy implementation.
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