I want create interface for singleton. But interface not can ban public constructor and describ static method. how to solve this of problems?
-
I have to be a fortuneteller to understand this question:( – Petar Minchev Jul 09 '10 at 07:03
-
You might want to check this out - http://stackoverflow.com/questions/2855245/abstract-base-class-to-force-each-derived-classes-to-be-singleton – this. __curious_geek Jul 09 '10 at 07:03
-
static methods are not valid in an interface – Chris Diver Jul 09 '10 at 07:04
-
It seems he wants to define the interface to force each implementation of the interface to be Singleton. – this. __curious_geek Jul 09 '10 at 07:05
-
Did you check the generic version I have suggested? It may be what you are trying to do. – Jaroslav Jandek Jul 09 '10 at 08:35
-
I vote to reopen now, though I was one of the closers. The question is now definitely clearer, than when I voted for closing. – Petar Minchev Jul 09 '10 at 08:50
3 Answers
You cannot have a ISingleton
interface for two reasons:
- Interfaces cannot have static members
- Interfaces cannot contain constructors
You could have a ASingleton
abstract class if you liked.

- 40,943
- 35
- 118
- 185
-
Error: A static member XXX cannot be marked as override, virtual, or abstract. – SkyN Jul 09 '10 at 07:26
You can't, basically. Interfaces can't contain static methods, and can't put any constraints on what kind of constructors are available.
You might be interested in my notion of static interfaces, which would allow the idea of enforcing a particular static member to be present - but it wouldn't allow you to enforce the absence of a constructor.

- 1,421,763
- 867
- 9,128
- 9,194
As others have said, you can't use an interface for that. What you can do is create a generic singleton class:
public static class Singleton<T> where T : new()
{
public static T Instance { get; private set; }
static Singleton() { Instance = new T(); }
}
This way you just use one generic class for all your singletons. Of course, you won't be able to initialize the singleton in different ways for different types (which can be changed implementing an interface on the instance or deriving classes).

- 9,463
- 1
- 28
- 30