Should member variables in singleton be declared as static?

Looking around the network, I saw this simple template that implements single-threaded single-threaded (in C #).

public sealed class MySingleton { private static readonly MySingleton _instance = new MySingleton(); private string[] _data = new string[10]; // Private constructor, so no outsiders have access. private MySingleton() { // Initialize _data member here } // Static method to provide access to instance public static MySingleton Instance { get { return _instance; } } public string GetStringCount { return _data.Length; } } 

I understand that the _instance member must be declared as static, as it is accessible from the static Instance() method.

But should other members be declared as static? By definition, singleton exists only once, so members can also exist only once (for one instance), just as static variables exist only once.

Should I declare _data as static?

  • Will there be any functional difference?
  • Any difference in performance?
  • Any other reasons for preferring static or non-static?
+4
source share
2 answers

If you have a singleton, you have one instance of the class. Class members should not be static (except for the support field of the instance property). If you have more than one static in your Singleton, you have not actually created a single Singleton, but many Singletones. The general advice is to use the static keyword only when absolutely necessary.

Storing your data cleanly in a single singleton instance as non-static class members.

+3
source

If you decide to use a singleton over a static class (see this and this ), then I think it makes sense to have instance members instead of static members.

+1
source

Source: https://habr.com/ru/post/1410961/


All Articles