Alex Meuer
Alex Meuer

Reputation: 1779

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?

Upvotes: 2

Views: 726

Answers (1)

smolchanovsky
smolchanovsky

Reputation: 1863

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.

Upvotes: 2

Related Questions