The Only C# .NET Singleton You’ll Ever Need

My colleague, Riaan Hanekom from NGenerics fame, showed me his perfect code for a singleton in C# .NET (version 2 and later). This generic class can create a singleton for any non-static class that has a default constructor.

This program is licensed under the Microsoft Permissive License (Ms-PL).  You should
have received a copy of the license along with the source code.  If not, an online copy
of the license can be found at http://www.codeplex.com/NGenerics/Project/License.aspx.
*/
public static class Singleton<T> where T:new()
{
private static readonly T instance = new T();
public static T Instance
{
get
{
return instance;
}
}
}
So simple, yet so complete…
Advertisements

4 Comments on “The Only C# .NET Singleton You’ll Ever Need”

  1. mmwaikar says:

    Hi,

    How are you using the google syntax highlighter on wordpress.com? I am sure you are not hosting your blog yourself.

    Please let me know.

    Thanks,
    Manoj.

  2. Anuj Varma says:

    The whole idea behind the singleton pattern is that it allows consumers to creation of a single INSTANCE of a class.

    When you mark a class as static (as in the example above), you have lost that basic criteria. This puts it in the same category as a utility class – which cannot be used to maintain state or changed down the road should you need more than one instance.

    For some key differences between why a singleton needs to stay non-static, check out my recent post below (or google static versus singleton classes).

    http://anujvarma.com/BlogEngine.net/post/2010/05/21/Singleton-in-C.aspx

    Thanks

  3. openlandscape says:

    Anuj,

    The above structure will indeed produce a single instance of class T. In my example I have not lost the basic criteria because class T is still an instance class. Class singleton is merely a construction class.

    I think you misunderstand how my Singleton is used. In my example T is equivalent to class Singleton in your blog post. My Singleton is the object that manages all the singleton objects I need. I am not trying to get a singleton of class Singleton, but rather of class T only.

    To state it another way let’s rename my Singleton class to SingletonManager. So to maintain a single instance of the Money class in your example, I would say SingletonManager<Money>.Instance.

    Also I avoid any concurrency issues, because the instance (T) is instantiated & assigned before any call is made to the Instance property.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s