LazyProperty Mutator

Mutator that takes a readonly property and caches the result, i.e. makes it lazy. This laziness is not thread safe and keeps a strong reference to the result.
  • Defined in: CciSharp.LazyProperty.dll

Example

  • original code
class Foo {
    [Lazy]
    public int Value { 
        get { return Environment.Ticks; } 
    }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
class LazyAttribute : Attribute {}
  • rewritten code
class Foo {
    int Value$Value; // compiler generated
    bool Value$Initialized;
    int GetValueUncached() { 
        return Environment.Ticks;
    }
    public int Value  {
        get {
            if(!this.Value$Initialized) {
                this.Value$Value = this.GetValueUncached();
                this.Value$Initialized = true;
            }
            return this.Value$Value;
        }
}

Requirements:

  • an non-virtual instance property with no setter and no arguments
  • marked with a LazyAttribute. It does not matter in which namespace or assembly this attribute lives, the tool only does name matching on the attribute
  • removes the LazyAttribute attribute when done.
  • the laziness is not thread safe
  • the cached value is stored as a strong reference. Use WeakLazyProperty for weak laziness.
  • lazy fields are annotated with NonSerialized so that they are not serialized.

Last edited Feb 27, 2011 at 9:11 PM by pelikhan, version 6

Comments

pelikhan Feb 27, 2011 at 9:11 PM 
thanks, updated.

NathanBaulch Feb 23, 2011 at 2:07 AM 
Value$Initialized should be a boolean