programming.torensma.net: Code Snippets

Singleton (c#)

Making a singleton in C#.

///
/// Simple singleton example.
/// See http://www.yoda.arachsys.com/csharp/singleton.html
/// for more information.
///
public class Singleton
{

	// singleton instance
	private static Singleton instance = null;

	// object for locking between threads
	static readonly object padlock = new object();

	// get singleton instance
	public static Singleton Instance
	{
		get
		{
			// lock to prevent multiple threads from creating
			// the singleton at the same time
			lock(padlock)
			{
				if (instance == null)
				{
					// create new singleton instance
					instance = new Singleton();
				}
				return instance;
			}
		}
	}

	///
	/// Private constructor so it can not be called from outside
	///
	private Singleton()
	{

	}
}

You can follow any responses to this entry through the RSS 2.0 feed.