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…

2 Responses to “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.


Leave a Reply