Daniel Bammer
Daniel Bammer

Reputation: 83

Is there a better way than static Instance Properties?

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...

Upvotes: 1

Views: 175

Answers (5)

spender
spender

Reputation: 120420

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.

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

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.

Upvotes: 0

James
James

Reputation: 82096

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.

Upvotes: 2

nickolayratchev
nickolayratchev

Reputation: 1206

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.

Upvotes: 0

maralfol
maralfol

Reputation: 178

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.

Upvotes: 0

Related Questions