Technology Lover Technology Lover - 25 days ago 7
C# Question

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?

Answer

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.