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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With