Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should member variables in singleton be declared as static?

Tags:

c#

singleton

Looking around the web, I've seen this simple pattern that implements a (thread-safe) singleton (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 needs to be declared as static because it is accessed from the static Instance() method.

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

Should I declare _data as static?

  • Will there be any functional difference?
  • Any performance difference?
  • Any other reason to prefer static or non-static?
like image 426
njr101 Avatar asked May 06 '12 09:05

njr101


2 Answers

If you have a Singleton you have one instance of a class. The class members must not be static (except for the Instance property backing field). If you have more than one statics in your Singleton you have actually created not one Singleton but many Singletons. A general advice is to use the static keyword only when absolutely necessary.

It is cleaner to store your singelton data inside your singleton instance as non static class members.

like image 56
Alois Kraus Avatar answered Nov 04 '22 04:11

Alois Kraus


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

like image 45
Eren Ersönmez Avatar answered Nov 04 '22 04:11

Eren Ersönmez