I am struggling using the 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 the Program class. I want to define an object from the Singleton class, for example: var data = Singleton.Instance; but I don’t know why I can’t do this. Also, I don’t know why I get the following error message when starting the program:
Unhandled Exception: System.NullRefernceException: Object reference not set to an instance of an object.
So how to fix this?
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. Now the program works, but the logic does not work. If you look at the main program, you will see that there is only "Hello World !!!" in the list. However, when I used the HasMessage method, this did not work. Because the program continues to show "There is a match." But he must show me "NO LINE !!!" since there is no coincidence.
So how to fix this?
c # design-patterns
Technology lover
source share