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,8441 gold badge26 silver badges55 bronze badges
asked Mar 3, 2016 at 14:02
2

2 Answers 2

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.

answered Mar 3, 2016 at 14:35

2 Comments

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 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.
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

answered Mar 3, 2016 at 14:19

1 Comment

typeof(Singleton2) will not instantiate static fields yet

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.