4

When I tried to use 2 different versions of the same class , they act actually the same.

I searched but can't find a satisfied answer for this question

What are the differences between Singleton and static property below 2 example, it is about initialization time ? and how can i observe differences ?

Edit : I don't ask about differences static class and singleton. Both of them non static, only difference is, first one initialized in Instance property, second one initialized directly

public sealed class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

public sealed class Singleton2
{
    private static Singleton2 instance = new Singleton2();

    private Singleton2()
    {
    }

    public static Singleton2 Instance
    {
        get
        {
            return instance;
        }
    }
}
Aria
  • 3,724
  • 1
  • 20
  • 51
rastbin
  • 95
  • 8
  • Possible duplicate of [Difference between static class and singleton pattern?](http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern) – Jay Mar 03 '16 at 14:03
  • 1
    [Here's an article](http://csharpindepth.com/Articles/General/Singleton.aspx) from c# in depth by Jon Skeet that will probably answer all your questions about the singleton pattern. – Zohar Peled Mar 03 '16 at 14:08

2 Answers2

1

Your first singleton implementation isn't thread safe; if multiple threads try to create a singleton at the same time it's possible for two instances to end up being created. Your second implementation doesn't have that flaw.

Other than that, they're functionally the same.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • I think second implementation is not thread safe too, but can be implemented. Do you mean that ? If yes, we can tell than they are exactly the same, but if we want to implement a mechanism for thread-safing, it is obvious that we can do that with second one – rastbin Mar 03 '16 at 14:42
  • 1
    @rastbin That is false. There is no way to create multiple instances of the class in the second instance. Obviously usage of the state of that *one* instance would need to be synchronized in either case, but the *creation* of the instance is thread safe in the latter and not in the former. – Servy Mar 03 '16 at 14:44
0

The instance of the Singleton class will be created the first time it is requested by the Singleton.Instance method.

The instance of Singleton2 will be created on initialization of its type which can be caused by several mechanisms. It will certainly be created before accessing any property or method on the Singleton2 class

mnwsmit
  • 1,198
  • 2
  • 15
  • 31