1

I'm very new to C# and currently I'm using this way to always use the same instance:

public class Sample{
    private Sample(){
        //initialize sth.
    }

    private static Sample _instance;
    public static Sample Instance{
        get{
            if(_instance == null)
                _instance = new Sample();
            return _instance;
        }
    }
}

Do you know a better way because it doesnt seem quite object-orientated to me...

Daniel Bammer
  • 83
  • 1
  • 6
  • 5
    there are pro and cons. Without more context, the question has no sense. Please explain the kind of application you are building – Steve B Oct 15 '12 at 13:26
  • It is a very broad subject. Search for Singleton Pattern and you will find numerous links. Here just one http://msdn.microsoft.com/en-us/library/ff650316.aspx – Steve Oct 15 '12 at 13:28
  • 1
    btw, the pattern you show is not thread-safe; you could get >1 different `Sample` instances – Marc Gravell Oct 15 '12 at 13:28
  • Summary: [link](http://www.codingwithoutcomments.com/) [link](http://jorudolph.wordpress.com/2009/11/22/singleton-considerations/) "caching data (especially from a DB) use the proxy pattern to do this..." – ceretullis Use Lazy when using Singleton in Multithread environment Use Dependency Injection to easily pass the Instance around and make unit testing comfortable. – Daniel Bammer Oct 16 '12 at 10:56

5 Answers5

2

The answer to your question is dependant on how you intend on using the property. Generally having a single static property across your full app is considered a bad idea as it can cause a lot of headaches when it comes to things like multi-threading environments/unit testing etc. However, there are scenarios where it is in-fact the correct approach e.g. logging.

Alternatively, you could use another approach where you pass the instance around to whoever needs it - more commonly know as Dependency Injection.

James
  • 80,725
  • 18
  • 167
  • 237
  • Finally, an answer that doesn't just provide yet-another-singleton-implementation. Other common problem scenarios would include unit-testing or multi-tenancy, (where in both cases you might find yourself suddenly needing isolated and different instances) – Marc Gravell Oct 15 '12 at 13:32
  • @MarcGravell I literally just updated my answer to mention unit testing as I realised I missed it! Yeah I think most people are too quick at jumping to code rather than actually assessing the design first. – James Oct 15 '12 at 13:32
0

It's OK if you want to have a Singleton class. This kind of pattern is used to have only one instance of this class.

maralfol
  • 178
  • 6
0

Yes, this approach is perfectly valid. However, be careful with initializing the instance of the singleton in the getter of the Instance property -- especially if it takes a long time to create said object.

nickolayratchev
  • 1,136
  • 1
  • 6
  • 15
0

Sure, use Lazy<T> and let the framework deal with the avoiding the race condition that your implementation yields.

private static Lazy<Sample> _instanceLazy = new Lazy<Sample>(() => new Sample());
public static Instance{get {return _instanceLazy.Value;} }

Definitely worth remembering that singleton sucks.

Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351
0

To create a Singleton, you can use multiple approaches.

If you write it explicitly, the best implementation method I found (nicely thread-safe) is:

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

But another method is to use an Inversion of Control framework such as Unity or Castle Windsor, which you can then configure to treat your class as a singleton.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • 1
    The code to write a singleton is much much simpler than that; what you show is a reasonable *lazily instantiated* singleton, though - which may be important if the cost of creating the singleton is important. In many cases, though, simply moving the readonly field up a level would be fine. – Marc Gravell Oct 15 '12 at 13:33