-1

Possible Duplicate:
What is a singleton in C#?

could some body please explain me singleton pattern? in c# please and what is it use for

Community
  • 1
  • 1
NoviceToDotNet
  • 10,387
  • 36
  • 112
  • 166
  • There are many articles that explain "why singleton is evil" if not applied correctly, maybe you should read that before you decide to use it in your project. – Abhijeet Kashnia Nov 01 '10 at 08:15

3 Answers3

4

A singleton is a class that only allows one instance of itself to be created.

An example of a singleton in C#.

public class Singleton
{
    private static Singleton _default;

    public static Singleton Default
    {
        get
        {
            if (_default == null)
                _default = new Singleton();
            return _default;
        }
    }

    private Singleton()
    { }

    public void SomeMethod()
    {
        // Do something...
    }
}

Then you would access it like:

Singleton.Default.SomeMethod();

http://en.wikipedia.org/wiki/Singleton_pattern

Alex McBride
  • 6,881
  • 3
  • 29
  • 30
  • Thread-safe singleton template for often usage: http://ilyatereschuk.blogspot.com/2013/12/c-simple-singleton-blank-for-everyday.html –  Dec 24 '13 at 06:54
3

A singleton pattern is a class that only ever allows one instance of itself to be created. If someone tries to create another instance, they just get a reference to the first one.

It's much derided due to people's tendencies to treat it as a God object where they just dump all sorts of stuff, and also because it can complicate unit testing. But it has its place if you know what you're doing, just like goto and multiple return points from functions :-)

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2
public class SingleTonSample
{
   private static SingleTonSample instance;
   public static SingleTonSample Instance
   {
        get
        {
           return instance?? new SingleTonSample();
        }
   }

   private SingleTonSample()
   {
    /// todo
   }

   public void Foo()
   {
     ///todo
   }
}

public class UseSingleton
{
    public void Test()
    {
       SingleTonSample sample = SingleTonSample.Instance;
       sample.Foo();
    }
}
Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83
  • I am pretty sure for this to work correctly your get needs to be: return instance?? (instance = new SingleTonSample()); otherwise instance will always be null when you call static method Instance and you will always return a new instance of SingleTonSample which is precisely not a singleton implementation. – eesh Aug 30 '11 at 17:33
  • @eesh. I wrote `return instance?? new SingleTonSample()` not return `return new SingleTonSample()`, try it and then say I'm sure. – Saeed Amiri Sep 03 '11 at 04:40
  • @eesh, In fact, `instance?? new SingleTonSample()` creates an instance when instance is null. – Saeed Amiri Sep 03 '11 at 05:51