Search code examples
c#.netconditional-operatornull-coalescing-operator

Thread safe singleton property in one line


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


Solution

  • 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(); }