Aug 7, 2015
Lazy struct
Code:
struct Lazy<T> { T value; bool init; Func<T> factory; public Lazy(Func<T> f) { factory = f; init = false; value = default(T); } public T Value { get { if (init) return value; else { init = true; return value = factory(); } } } }
Variant with a single argument
is useful when we want to use a non-local function and don't want to use closure (for better performance)
Code:
struct Lazy<TVal, TArg> { TVal value; TArg arg; bool init; Func<TArg, TVal> factory; public Lazy(Func<TArg, TVal> f, TArg arg) { factory = f; init = false; value = default(TVal); this.arg = arg; } public TVal Value { get { if (init) return value; else { init = true; return value = factory(arg); } } } }
Subscribe to:
Posts (Atom)