Friday, September 14, 2007

Singleton Pattern

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 [4]  
kick it on DotNetKicks.com
Friday, September 14, 2007 8:37:03 PM (GMT Standard Time, UTC+00:00)
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
Friday, September 14, 2007 9:11:25 PM (GMT Standard Time, UTC+00:00)
wow that is really slick thanks
Saturday, September 15, 2007 12:32:26 AM (GMT Standard Time, UTC+00:00)
You're welcome. Let me know if you have any trouble with it.
Cade Roux
Friday, June 26, 2009 5:51:50 AM (GMT Standard Time, UTC+00:00)
Excuse me. We are made to persist. That's how we find out who we are. Help me! Looking for sites on: Cialis generic. I found only this - how long does cialis last. To find out about vbulletin, go to Free pills viagra and cialis for all customers. With best wishes ;-), Patrice from Spain.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview