2

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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 3
    With [`Lazy`](https://learn.microsoft.com/en-us/dotnet/api/system.lazy-1?view=net-7.0) :) – Fildor Jan 05 '23 at 07:19
  • I know it makes more sense to use Lazy. I was stubborn to write a single line but failed :') Thanks.. – Oguz Demirel Jan 05 '23 at 07:39
  • 1
    The round wheel version of your invention - https://stackoverflow.com/questions/2155688/what-is-a-singleton-in-c (in particular https://csharpindepth.com/Articles/Singleton by *the* Jon Skeet) – Alexei Levenkov Jan 05 '23 at 07:40
  • (Updated title to match the task rather than attempted solution, but could not add proper code-golf tag as it is banned for obvious reason... Feel free to improve title more if you feel my edit did not exactly match your goal) – Alexei Levenkov Jan 05 '23 at 07:44

2 Answers2

4

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(); }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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>

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • 1
    the default thread-safety mode (if `true` not specified) is `LazyThreadSafetyMode.ExecutionAndPublication`, which is what `true` produces, so... you can probably skip that ([source](https://learn.microsoft.com/en-us/dotnet/api/system.lazy-1.-ctor)); nit: `_lazyInstance` should be `readonly` – Marc Gravell Jan 05 '23 at 07:28