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?