« FMSummit 2014 in Den … | Home | fm conference »

Tip of the day: Using computed property with weak reference

Often we need to keep a property somewhere, but it needs to be a weak reference. So if the target goes out of scope, our reference should become nil. Now we can of course use WeakRef class directly for this. But that requires some work and casting on every access. It is much nicer to wrap it in a computer property. This way the compiler can check types when using the property. Internally we map back to the weakRef object. So check this code:

ComputedProperty ParentWindow As window1
Sub Set(value as ParentWindow) if value<>Nil then mParentWindow = new weakref(value) else mParentWindow = nil end if End
Function Get() as ParentWindow if mParentWindow<>nil then dim o as variant = mParentWindow.Value Return o end if End
End ComputedProperty
Property Private mParentWindow As WeakRef

As you see we have a private property with the actual weakRef. The computed property getter checks if we have a WeakRef and provides value of it. We use a variant to avoid the need of explicit casting. For the setter we either set our weakRef property to nil or a new weakRef pointing to the target value.
Please use weak references always for references in data structures where a leaf references back to the tree.
15 06 14 - 12:50