I just tried to implement Singleton pattern to WinForms ,so that only one instance of a form stays in the Application life ,but i face a difficulty
I want to throw exception if the instance of singleton exists and return same instance reference at the same time.
SingletonForm.cs
public class SingletonForm : BaseFormcs
{
private static SingletonForm _instance;
//To stop new keyword from instantiation
private SingletonForm()
{ }
public static SingletonForm GetInstance()
{
if (_instance == null)
return _instance = new SingletonForm();
else
{
throw new Exception("Form already exists"); // execution returns from here
return _instance; // Warning : Unreachable code detected
//I also want to return instance reference.
}
}
}
You either throw an Exception, or return an instance. In the case of a Singleton, no Exception should be thrown, just return the instance if it exists.
The Singleton pattern shouldn’t stop you (or even warn you) from calling GetInstance many times. It should just return the same instance that was created the first time around.
Throwing an exception returns immediately from the function, because it means that an unexpected error occurs. In another situation, you might want to throw an exception, but only if some condition is true (e.g. argument validation failed). Otherwise, you return a value. Here’s an example: