Table of Contents

Class LazyGet<TValue>

Namespace
ToSic.Sys
Assembly
ToSic.Sys.Core.dll

Simple helper class to use on object properties which should be generated once. Similar to Lazy(), but the generator function is passed in on the Get() call, not on the constructor.

[InternalApi_DoNotUse_MayChangeWithoutNotice]
public class LazyGet<TValue>

Type Parameters

TValue
Inheritance
object
LazyGet<TValue>
Derived

Remarks

Important for properties which can also return null, because then checking for null won't work to determine if we already tried to retrieve it.

Constructor is empty.

In case you're wondering why we can't pass the generator in on the constructor: Reason is that in most cases we need real objects in the generator function, which doesn't work in a static context. This means that if the = new LazyGet() is run on the private property (which is the most common case) most generators can't be added.

Typical use cases:

  1. Properties which could validly return a null, in which case ?.Get() would run too often.
  2. Properties which must - in rare cases, be reset
  3. Properties which must check if they were already created (like Lazy())
  4. Properties which have non-nullable types like tuples, which can't self-detect if they are still empty
  5. Methods which behave like properties but as methods (typically to prevent serialization), so they don't have a backing field, needing additional code

Fields

Value

protected TValue? Value

Field Value

TValue

Properties

IsValueCreated

Determines if value has been created. The name IsValueCreated is the same as in a Lazy() object

public bool IsValueCreated { get; protected set; }

Property Value

bool

Methods

Get(Func<TValue>)

Get the value. If not yet retrieved, use the generator function (but only once).

public TValue? Get(Func<TValue> generator)

Parameters

generator Func<TValue>

Function which will generate the value on first use.

Returns

TValue