class Program
{
static void Main(string[] args)
{
// Get the Singleton instance
Singleton singletonInstance = Singleton.Instance;
// Call a method on the Singleton instance
singletonInstance.PrintMessage();
// Trying to create another instance will return the existing instance
Singleton anotherInstance = Singleton.Instance;
// Check if both instances are the same
bool areSameInstances = ReferenceEquals(singletonInstance, anotherInstance);
Console.WriteLine($"Are the instances the same? {areSameInstances}");
}
}
The Singleton design pattern in C# is powerful for ensuring there's only one instance of a class and providing global access to that instance. By carefully designing and implementing the Singleton pattern, you can achieve efficient resource management, maintainability, and thread safety in your applications. However, it's important to consider its implications, such as global state and concurrency issues, and use it judiciously where its benefits outweigh its drawbacks.