Then Cyrus decided he wanted to support weak references.  A weak reference is one that the GC can decide to release if there are no other references to it.  

 

For our LazyLoader, that would mean that you create the item when demand appears, and it may go away if it’s not needed, and then it’ll come back later if needed again.  At that point, you really do have a cache.

 

To do this, Cyrus first built some cool classes to handle weak and strong references.  You could think of IStrongReferenceas being the same as a regular reference in C# today.

 

interface IReference<A>

{

    A Value { set; }

 

    IOptional<A> Target { get; }

}

class StrongReference<A> : IReference<A>

{

    IOptional<A> target = None<A>.Instance;

 

    public IOptional<A> Target

    {

        get

        {

            return target;

        }

    }

 

    public A Value

    {

        set

        {

            target = new Some<A>(value);

        }

    }

}

class WeakReference<A> : IReference<A>

{

    System.WeakReference reference;

 

    public WeakReference()

    {

        Value = default(A);

    }

 

    public IOptional<A> Target

    {

        get

        {

            IOptional<A> target = (IOptional<A>)reference.Target;

            if (target == null)

            {

                return None<A>.Instance;

            }

            else

            {

                return target;

            }

        }

    }

 

    public A Value

    {

        set

        {

            reference = new WeakReference(new Some<A>(value));

        }

    }

}

 

Note that you can have a strong or weak reference to ‘null’, and that’s not the same thing has not having a reference as all.  ‘null’ is a value, and None<> is not a value.  Ahh, the power of IOptional<>.

 

One other thing Cyrus mentioned is that he might put these in a References namespace, and refer to them with FQNs:

 

          References.IReference

          References.Weak

          References.Strong

 

That reads well, but C# wasn’t really built for it, IMO.  A question of style, I guess.