Singleton Pattern

09.14.07

The singleton pattern in C# is very simple to implement and very useful. This pattern ensures that there is only one instance of its self providing a global point of access. There are different ways of doing this but I like to use the example below  because it is thread safe and clean.

public class User
{
     private int _userId = 1;
     private static User _instance = new User();
     static User()
     {
     }
     private User()
     {
     }
     public int UserId
     {
         get
         {
             return _userId ;
         }
         set
         {
             _userId = value;
         }
     }
     public static User Instance
     {
         get
         {
             return _instance;
         }
     }
}

Here is a quick test I wrote in NUnit that shows how it is used and comfirms there is only one instance.

[Test]
public void TestSingleton()
{
     User sngle1 = User.Instance;
     sngle1.UserId = 1;
     User sngle2 = User.Instance;
     sngle2.UserId = 2;
     Assert.AreEqual(sngle2.UserId, sngle1.UserId);
}

More Info:
Everything you need to know about C# singleton.
More Patterns

Comments (3) -

9/14/2007 3:37:03 PM #

Cade Roux

This is a base class which gives you singleton without re-implementation in every derived class (and your choice whether to have only private constructors or not):

public class SingletonBase<T>
      where T : class
    {
        static SingletonBase()
        {
        }

        public static readonly T Instance =
          typeof(T).InvokeMember(string.Empty,
                                 BindingFlags.CreateInstance |
                                 BindingFlags.Instance |
                                 BindingFlags.NonPublic,
                                 null, null, null) as T;
    }

Cade Roux

9/14/2007 4:11:25 PM #

Aaron

wow that is really slick thanks

Aaron

9/14/2007 7:32:26 PM #

Cade Roux

You're welcome.  Let me know if you have any trouble with it.

Cade Roux