Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(); }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading