0

How can I write a class in C# that only returns the "same" instance of an object? Is this effectively a singleton or different? This was mentioned in the book Effective Java 2nd addition.

I use C# 4.0 (no technology barrier).

GurdeepS
  • 65,107
  • 109
  • 251
  • 387
  • Yes, this is the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern – Paul Sasik May 11 '12 at 13:41
  • Well best way, as long as it can stay static is just to have a static class, if not use a singleton pattern, there is many posts here about it already http://stackoverflow.com/questions/3136008/is-this-singleton-implementation-correct-and-thread-safe – Tenerezza May 11 '12 at 13:42

3 Answers3

4

Yes, this is a Singleton pattern. You'll find an excellent discussion based on our own Jon Skeet's C# implementation here.

Community
  • 1
  • 1
David M
  • 71,481
  • 13
  • 158
  • 186
1

If your Singleton object is expensive to create, but isn't used every time your application runs, consider using Lazy.

public sealed class LazySingleton
{
    private readonly static Lazy<LazySingleton> instance = 
        new Lazy<LazySingleton>(() => new LazySingleton() );

    private LazySingleton() { }

    public static LazySingleton Instance
    {
        get { return instance.Value; }
    }
}
Oblivion2000
  • 616
  • 4
  • 9
0
using System;

namespace DesignPatterns
{
    public sealed class Singleton
    {
        private static volatile Singleton instance = null;

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                   Interlocked.CompareExchange(ref instance, new Singleton(), null);

                return instance;
            }
        }
    }
}
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92