Search code examples
c#weak-references

Is it okay to initialise WeakReference with a null value?


I have a class which will only ever have a single instance at a time. It's essentially a singleton that is destroyed when no external references are held and re-instantiated when you need a new reference later.

private static readonly WeakReference<Foo> weakInstance = new WeakReference<Foo>(null);

The reason for the above code is because I have native iOS callbacks (which must be static functions) but which need to pass data to the current instance.

tl;dr Is it safe to initialise a WeakReference to null and set the target later? Is this a code smell?

Edit: As @smolchanovsky pointed out, I could just instantiate the weak reference when I need to set it. This results in:

if (weakInstance == null)
{
    weakInstance = new WeakReference<Foo>(this);
}
else
{
    weakInstance.SetTarget(this);
}

or

// Overwrite the existing WeakReference object
weakInstance = new WeakReference<Foo>(this);

Is there a reason to pick one of these over the other?


Solution

  • Why not use this?

    public sealed class Singleton
    {
        private static WeakReference<Singleton> weakInstance;
    
        public WeakReference<Singleton> Instance
        {
            get
            {
                if (weakInstance == null)
                    weakInstance = new WeakReference<Singleton>(this);
                else
                    weakInstance.SetTarget(this);
                return weakInstance;
            }
        }
    }
    

    Note that this isn't a thread safe solution.