spiderplant0
spiderplant0

Reputation: 3952

How do I use this singleton example

This page does a good job of describing how to create c# singletons, but it doesn't seem to explain how you actually use them.

http://msdn.microsoft.com/en-us/library/ff650316.aspx

So if I were to create this singleton below, how do I kick things off (I don't think I can instantiate it directly) and if I don't have an instance object how to I access it - e.g. how do I read and write to property prop1

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();

   private Singleton(){}

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

   public int prop1 {get; set;}
}

Upvotes: 1

Views: 160

Answers (4)

Wonderbird
Wonderbird

Reputation: 374

Singleton.Instance.prop1 = 12;

Upvotes: 0

KillaKem
KillaKem

Reputation: 1025

You only create the instance once, So you will have something like this

public sealed class Singleton
{
   private static readonly Singleton instance;
   private bool initialised = false; 

   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
        if(initialised)
          return instance; 
        else {
               initialsed = true;
               instance = new Singleton();
               return instance; 
             }
      }
   }

   public int prop1 {get; set;}
}

Upvotes: 0

Mike Norgate
Mike Norgate

Reputation: 2431

You can access the instance by using

Singleton.Instance

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35852

To use a singleton class, you simply call it's public static instance property. For example, suppose that you have a logger, and you don't want other developers to always instantiating it:

public class Logger
{
    private static Logger logger = new Logger();

    private Logger() { }

    public static Logger Instance
    {
        get
        {
            return logger;
        }
    }

    public void Log(text)
    {
        // Logging text
    }

    public int Mode { get; set; }
}

You should log this way:

Logger.Instance.Log("some text here");

In your case, to read/write Mode property, you should write:

Logger.Instance.Mode = 1;
int mode = Logger.Instance.Mode;

Upvotes: 3

Related Questions