3
class MyClass
{
    private MyClass(){}

    private static MyClass instance;

    public static MyClass Instance
    {
       get
       {
          return instance=instance??new MyClass();
       }
    }
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • 2
    In terms of multithreading absolutely no. If there is only one thread why do you need singleton? You should add locks to the code. Concerning `??` it will work, but I'd rather write it in more common way, with `if`. – Alex Sikilinda Mar 21 '15 at 19:09
  • 3
    Please read [Jon Skeet's Singleton patterns](http://csharpindepth.com/articles/general/singleton.aspx). Your code is what is shown as the bad example in "First version - not thread-safe". – Matt Johnson-Pint Mar 21 '15 at 19:31
  • The correct way is to NOT define a singleton. Its part of the STUPID design acronym for a reason. Think SOLID design instead. – Aron Mar 21 '15 at 19:41
  • Thank you very much for noticing me about multithreading safaty , i even didn't knew about that. – Հայկ Գրիգորյան Mar 21 '15 at 22:19
  • When someone mentions a singleton I always wonder in what scope? Just 1 instance per thread, per (virtual) machine, cluster of machines, data center or really just 1 in the world ever? – Kwebble Mar 21 '15 at 23:32
  • Btw can someone provide example when my first version creates two instances of the MyClass in multiple threads ? i've just tryed it in two threads and even put preakpoint at MyClass constructor , but it creates only one instance. – Հայկ Գրիգորյան Mar 22 '15 at 13:45

1 Answers1

5

Personally, I think that singleton is an anti-pattern.

That said:

Your code isn't safe because

return instance = instance ?? new MyClass();

is not atomic.

Lazy<T> takes care of a lot of the issues regarding the creation of singleton classes.

So:

public class MyClass
{
    public static MyClass Instance
    {
        get
        {
            return instanceLazy.Value;
        }
    }

    private static Lazy<MyClass> instanceLazy = 
        new Lazy<MyClass>(() => new MyClass());

    private MyClass()
    {
    }
}
Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351
  • Note that Lazy is available in .NET 4 and higher. (Reference source is [here](http://referencesource.microsoft.com/#mscorlib/system/Lazy.cs,8b99c1f377873554) if you want to implement something similar in an earlier version.) – yoyo Mar 21 '15 at 20:38
  • Thank you for response. What about thread safaty problem which mentioned above ? this satisfies multithreading safaty criterias ? – Հայկ Գրիգորյան Mar 21 '15 at 22:21
  • @ՀայկԳրիգորյան Yes. In its default mode, `Lazy` is thread safe. – spender Mar 22 '15 at 00:31