WeakLazyProperty Mutator

Mutator that takes a property getter and caches the result in a weak reference. This laziness is not thread safe and assumes that the property value is never null.
  • Defined in: CciSharp.WeakLazyProperty.dll

Example

  • original code
class Foo {
    [WeakLazy]
    public object Value { 
        get { return Environment.Ticks.ToString(); } 
    }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
class WeakLazyAttribute : Attribute {}
  • rewritten code
class Foo {
    WeakReference value$Weak;
    string GetValueUncached() { 
        return Environment.Ticks.ToString();
    }
    public object Value  {
        get {
            var value = this.value$Weak != null ? (this.value$Weak.Value as string) : null;
            if(value == null)
                this.value$Weak = new WeakReference(value = this.GetValueUncached());
            return value;
        }
    }
}

Requirements:

  • an non-virtual instance property with no setter and no arguments
  • marked with a WeakLazyAttribute. It does not matter in which namespace or assembly this attribute lives, the tool only does name matching on the attribute
  • the property type is a reference type
  • it is assumed that the property value is never null
  • removes the WeakLazyAttribute attribute when done.
  • the laziness is not thread safe
  • lazy fields are annotated with NonSerialized so that they are not serialized.

Last edited Dec 30, 2009 at 8:45 AM by pelikhan, version 3

Comments

No comments yet.