Create a Singleton in C#

Sometimes you need an object instance rather than a static class but you really want that object instance to be globally unique to your application, e.g. there can be only one.  Enter the singleton pattern:

 
public class MySingleton
{
 
private static volatile MySingleton _instance;
 
private static object _sync = new object();
 
public static MySingleton Instance
{
 
get
{
 
if (_instance == null)
{
 
lock (_sync)
{
 
if (_instance == null)
{
 
_instance = new MySingleton();
 
}
}
}
return _instance;
}
 
}
 
private MySingleton()
{
}
 
public int GetInt()
{
return 12;
}
 
}

You then access your new singleton methods like this:

MySingleton.Instance.GetInt()

And there you have it!  A singleton of which you can be sure there is only one instance globally across your application domain.

This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *