inheritable singleton pattern for windows forms
Hello!
I'm rather new to C# and developing my first commercial application in that language. It contains some forms, and only one instance of each form can exist in the running application. So, each form implements the Singleton pattern is such way:
public class Report: Form {
private static Report _instance;
protected Report(){InitializeComponent(); ... }
public static Form instance {get {
if (_instance == null) _instance = newReport();
return _instance;}}
...
}
So, this code is duplicated in every single form in my application and the only difference between forms is shown inbold in the example. I want to get rid of that duplication, for example, by defining a base clase which inherits Form and implements Singleton behaviour.
As creating virtual static method, which could return
typeof(corresponding_form_class)
is impossible in C#, I tried to use generics:
public class SingletonForm: Form<T> where T: Form, new() {
private static T _instance;
protected SingletonForm(){}
public static T instance {get {
if (_instance == null) _instance = new T();
return _instance;}}
...
}
And then defining concrete form classes this way (looks weird):
public class ConcreteForm: SingletonForm<ConcreteForm>{
...
}
It compiles and runs, but when I try to open Concrete form in the IDE designer, I receive an error message that says that the base class cannot be loaded.
And this is where I am now. Waiting for clues from experienced C# programmers :)

