Singleton Class


NOTE: the concepts presented in this article are now considered obsolete possibly because better alternatives are available.

This article is considered obsolete. Take a look here instead. This snippet shows you how to implement a Singleton class in C#.
	class Singleton
{
    private static Singleton singleton = null;
    public static Singleton Instance()
    {
        if (null == singleton)
            singleton = new Singleton();

        return singleton;
    }

    private Singleton()
    {
    }
}

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Friday, November 16, 2007 2:47:46 PM Sandro said:
Your solution is not thread save. If the Instance() method is called by two callers almost at the same time it might be possible that they get back two different instances.

The following code is thread save. Aditinally you could replace the Instance method with a property:

class Singleton
{
private readonly static Singleton singleton = new Singleton();
public static Singleton Instance()
{
return singleton;
}

private Singleton()
{
}
}
On Saturday, November 17, 2007 10:22:59 AM Imar Spaanjaars said:
Hi Sandro,

Yep, you're right. Thanks for posting a follow up. I marked the article as obsolete.

Imar
On Monday, March 24, 2008 7:58:03 AM Ranjan said:
Hi All,

I found a better code from the link below. Its Thread safe

http://www.esus.com/javaindex/pcalgorithms/patterns/crthreadsafesing.html

public class ExampleSingleton {

  private static ExampleSingleton instance;

  public static ExampleSingleton getInstance() {
    if( instance == null ) {
      synchronized( ExampleSingleton.class ) {
        if ( instance == null ) {
           instance = new ExampleSingleton();
        }
      }//sync ends
    }

    return instance;
  }
}
On Monday, May 25, 2009 4:51:07 PM sandip salokya said:
/*
Is this a proper way to crate singleton class for databse connection?
or it is not necessary to create singleton class for the databse connection?
by writing
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationDB.ConnectionString))
GC will free SqlConnection object

need suggestion

*/
public class Dal
    {
        private static String connectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

        private static SqlConnection connection = null;


        // call GetConnection by Dal.GetConnection()
        public static SqlConnection GetConnection()
        {
            lock(typeof(SqlConnection)){
                if (connection != null || connection.State == ConnectionState.Open)
                    connection = null;
                if (connection == null)
                {
                    connection = new SqlConnection(connectionString);
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();

                }

                else
                    return connection;
            }
            
           return connection;
        }

        // call CloseConnection by Dal.CloseConnection()
        public static void CloseConnection()
        {
            if (connection != null && connection.State == ConnectionState.Open)
            {
                connection.Close();
                connection.Dispose();
            }
                
        }
        
        private Dal() { }

        
    }
On Monday, May 25, 2009 4:58:58 PM Imar Spaanjaars said:
Ouch.... Very bad idea. This way all your clients share a single, open connection which means the second one has to wait until the first one is ready. Guaranteed to bring your app to a grinding halt.

Instead, give each client its own connection instance.

Cheers,

Imar
On Monday, July 20, 2009 4:37:56 PM candy said:
where exactly is this pattern useful?
I am yet to find a practical scenario where a singleton makes sense
On Monday, July 20, 2009 6:05:58 PM Imar Spaanjaars said:
Hi candy,

There are many situations where this can be useful. For example, if you want an object to store some state that should be globally available. You don't want to have multiple objects laying around as they might get out of sync.

You can also use it to limit the number of instances of other classes that get created. For more info:

http://en.wikipedia.org/wiki/Singleton_pattern
http://msdn.microsoft.com/en-us/library/ms954629.aspx

But: don't worry. If you can't think of a good reason for a singleton, you probably don't need it ;-)

Imar

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.