Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use this Singleton Class in C#?

I am struggling with using Singleton design pattern. I am trying to use it in this simple console application. I have a problem with it in the Main method in Program class. I want to define object from the Singleton class such as: var data = Singleton.Instance; but I don't know why I can't do that Also, I don't know why I am getting the following error message when I run the program:

Unhandled Exception: System.NullRefernceException: Object reference not 
  set to an instance of an object.

So how to fix that?
Singleton Class:

namespace Singleton
{
    class Singleton
    {
        //Variable
        private static Singleton instance;
        private List<string> Messages;
        //Constructor
        private Singleton() { }
        //Property
        public static Singleton Instance
        {
            get 
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
        //Methods
        public void Message(string message)
        {
            Messages.Add(message);
        }

        public bool HasMessage(string message)
        {
            return Messages.Contains(message);
        }
    }
}

Program Class:

namespace Singleton
{
    class Program
{
    static void Main(string[] args)
    {
        var data = Singleton.Instance;
        Singleton.Instance.Message("Hello World!!!");
        if(Singleton.Instance.HasMessage("12"))
            Console.WriteLine("NO STRING!!!");
        else
            Console.WriteLine("There is a match");

    }
}
}

UPDATE:

Guys, I really appreciate your help so far. The program is working now but the logic is not working. If you look at the main program, you will see that the list only has "Hello World!!!". However, when I used the HasMessage method doesn't work. Because the program keeps showing "There is a match". But it should show me "NO STRING!!!" as there is no match. So how to fix that?

like image 885
Technology Lover Avatar asked Jan 15 '13 04:01

Technology Lover


People also ask

What is singleton class in C?

You have a class that must only ever be instantiated once, and you need to provide a way for clients to access that class in such a way that the same, single object is returned each time. This is commonly referred to as a singleton pattern, or a singleton class.

How would you use a Singleton?

You use a singleton when you need to manage a shared resource. For instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource. Or a database connection or a file manager etc.

How do you handle a class Singleton?

We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method.

Where do we use singleton class?

Singleton classes are used for logging, driver objects, caching and thread pool, database connections. An implementation of singleton class should have following properties: It should have only one instance : This is done by providing an instance of the class from within the class.


2 Answers

Your field Messages is not initialized to anything. That is why you are getting the exception. In your class do:

 private List<string> Messages = new List<string>();

You may also look at Thread Safe Singleton implementation by Jon Skeet

EDIT:

Based on the updated question. Your Check and Message are opposite. It should be:

if (Singleton.Instance.HasMessage("12"))
    Console.WriteLine("There is a match");
else
    Console.WriteLine("NO STRING!!!");

Your method HasMessage returns true if the passed parameter is present in the list and false otherwise.

like image 84
Habib Avatar answered Oct 02 '22 14:10

Habib


It looks like you're almost there. Consider rewriting your code like this:

class Singleton
{
    //Variable
    private static Singleton Instance;
    private List<string> Messages;
    //Constructor
    private Singleton() 
    {
     Messages = new List<string>(); //Make sure to instantiate instance types before use. 
    }
    //Property
    public static Singleton GetInstance()
    {
            if (Instance == null)
            {
                Instance = new Singleton();
            }
            return Instance;

    }
    //Methods
    public void Message(string message)
    {
        Messages.Add(message);
    }

    public bool HasMessage(string message)
    {
        return Messages.Contains(message);
    }
}

There are some helpful C# tutorials for design patterns on this site.

like image 37
jake Avatar answered Oct 02 '22 14:10

jake