I've been reading about how to implement a thread safe singleton class. I've managed to find many different ways of creating one, however I have not managed to find information about where exactly I'm supposed to put my properties and methods etc. in the class.
For example:
public sealed class Singleton
{
//Do I put properties here?
private Singleton() {}
public static Singleton GetInstance()
{
return NestedSingleton.singleton;
}
class NestedSingleton
{
//Do I put properties here?
internal static readonly Singleton singleton = new Singleton();
static NestedSingleton() {}
//Do my methods go here
}
//or here?
}
The methods would go in the outer class. The only purpose of the nested class is to enforce particular timing of the initialization of the singleton instance of the outer class.
Don't forget that your GetInstance
method returns a reference to Singleton
- not NestedSingleton
. Indeed, NestedSingleton
is private, so code outside Singleton
doesn't even know about its existence. You might want to make it a static
class, too. (That would stop you from even trying to add instance members to it.)
Personally I would only use this form if I wanted really tight control over initialization - normally I'd just use a field in the Singleton
class itself. (Or a Lazy<T>
...) That's a bit simpler. If you haven't already come across my article on singleton implementations in C#, you might want to have a look at it. (I suspect you've already seen it, but...)
See more on this question at Stackoverflow