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;
}
}
}
-
Possible duplicate of Difference between static class and singleton pattern?Jay– Jay2016年03月03日 14:03:14 +00:00Commented Mar 3, 2016 at 14:03
-
1Here's an article from c# in depth by Jon Skeet that will probably answer all your questions about the singleton pattern.Zohar Peled– Zohar Peled2016年03月03日 14:08:05 +00:00Commented Mar 3, 2016 at 14:08
2 Answers 2
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.
2 Comments
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
1 Comment
typeof(Singleton2)
will not instantiate static fields yet