Home > Software engineering >  Thread safe singleton property in one line
Thread safe singleton property in one line

Time:01-05

How can I write the following code in one line?

   private static LockSDP instance;
        private static readonly object _lock = new();
        public static LockSDP GetInstance
        {
            get
            {
                if (instance is null) lock (_lock) instance ??= new();
                return instance;
            }
        }

error

CodePudding user response:

not everything can be one line; however, this can perhaps be easier; you could use Lazy<T>, but for a simple static here where you're mostly after deferred instantiation, I would probably lean on static field behaviour and a nested class:

public static LockSDP GetInstance => LockProxy.Instance;
private static class LockProxy { public static readonly LockSDP Instance = new(); }

CodePudding user response:

I'd probably prefer Marc's answer but just so it's there:

private static readonly Lazy<LockSDP> _lazyInstance = 
    new Lazy<LockSDP>(() => new LockSDP()); // Default is Threadsafe access.

public static LockSDP Instance => _lazyInstance.Value;

And yes: I do realize it is still 2 lines :/

For reference: Lazy<T>

  • Related