Reputation: 6170
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?
}
Upvotes: 2
Views: 149
Reputation: 7416
You can also take a look at this post , this is the Singleton implementation I use in some of my projects.
In C# < 4, you can use :
public class Singleton
{
private static Singleton _instance;
private static object _lock = new object();
private Singleton(){}
public static Singleton Instance
{
get
{
if(_instance == null)
{
lock(_lock)
{
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}
Or in C# 4
public class Singleton
{
private Singleton(){}
private static readonly Lazy<Singleton> _instance = new Lazy<Singleton>(()=>new Singleton());
public static Singleton Instance{ get {return _instance.Value; } }
}
This implementation is thread safe.
Upvotes: 0
Reputation: 1499770
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...)
Upvotes: 6
Reputation: 887215
You should put all instance members in the outer class.
The inner class is a private holder type which only exists to lazily initialize the singleton value.
It should be static
.
Upvotes: 3