6
votes

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?
2
The other members are related to the object which is created on your third line and named _instance. If you specify _data as static - it would be a class member, not an object member. So there is nothing to do with syntax or best practices, but with your intentions and aims.zerkms
@zerkms clearly he knows that, but since it's a singleton the data would only exist once either way - there would be no real difference.harold
@njr are you using the singleton as a workaround to let a static class implement interfaces (then I'd keep everything static as much as possible to match the original intent), or for some other reason?harold
@harold: indeed, it is about semantics. But I wouldn't make the singleton some special and exceptional case, to not confuse further readerszerkms
@harold: I'm using a singleton to be more flexible, since I may want to pass the object as a parameter in the future. To be honest, for the moment I could just use a static class. I was really just curious if there was any "real-world" difference between static and non-static members for singletons.njr101

2 Answers

5
votes

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.

2
votes

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.