What is the difference between a static property and a single property?

A singleton implemented with C # might be like this:

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

If I use static to implement it, for example:

 public static class Globals{ public static Singleton Instance = new Singleton(); } 

thus, the application should also receive only one instance for the entire application. So what is the difference between the two approaches? Why not use a static member directly (simpler and more direct)?

+7
source share
2 answers

If you use the second approach:

 public static class Globals{ public static Singleton Instance = new Singleton(); } 

There is nothing stopping you from doing:

 Singleton anotherInstance = new Singleton(); // Violates singleton rules 

You also will not have the same lazy initialization as your first version (attempts), plus you use a public field that does not allow you to have the same flexibility in the future if you need to change what happens when the value is retrieved.

Note that .NET 4 provides a potentially better approach to creating singleton:

 public class Singleton { private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton()); private Singleton() {} public static Singleton Instance { get { return instance.Value; } } } 

This is good because it is completely lazy and completely thread safe, but also simple.

+8
source

Below are some differences between static and Singleton:

  • Singleton is the template, and static is the keyword.
  • The Singleton class can have a static and non-stationary method, but a static class can have only static elements and methods.
  • We can implement the interface in the Singleton class, but in the static class we cannot implement the interface.
  • We can extend the Singleton class while we can not a static class, i.e. the Singleton class can be obtained from any type of class.

for more static vs Singleton

-one
source

All Articles