0

As mentioned in this other question, I'm looking for a way not to create always another instance of a class. I know this can be done, using a singleton.

As I've seen that quite some design patterns are handled by C# libraries, I believe this should be the case for the singleton design pattern, but I don't find an ISingleton interface, which I could implement.

Does anybody know in which library using which_library; I can find an ISingleton interface or should I create a singleton class from scratch?

Dominique
  • 16,450
  • 15
  • 56
  • 112
  • What members would you expect an `ISingleton` interface to expose? – John Wu Dec 19 '22 at 07:34
  • Why do you need an interface to represent an instance of a class that never changes (neither its static nor its dynamic type)? – PMF Dec 19 '22 at 07:35
  • Even if there were such an interface, you'd still have to define a class that implemented that interface, so there's the same amount of work either way. A singleton class basically requires a private static field to store the instance and a public static property to expose it, so an interface couldn't help there anyway. If I'm not mistaken, static interface members have been introduced very recently but they haven't existed for nearly two decades. – jmcilhinney Dec 19 '22 at 07:37
  • This is nonsense: `using which_library;`. You don't import a library. You import a namespace. That namespace may or may not match the name of the assembly - the library - that's it's members are declared in. Also, members of multiple namespaces can be declared in the same assembly and members of the same namespace can be declared in different assemblies. – jmcilhinney Dec 19 '22 at 07:39
  • If such an interface existed, all you would have to do would be type the name into the search page of the .NET documentation site. You don't need to ask us if a first-party type exists in .NET. – jmcilhinney Dec 19 '22 at 07:40
  • @jmcilhinney Even a static property in an interface wouldn't help, because interfaces still cannot contain fields. So it would be possible to implement the `Instance` property of a singleton in an abstract base class, but not in an interface. – PMF Dec 19 '22 at 07:46
  • 1
    Judging by that other question - you don't need singleton, but just `ConcurrentDictionary` (so thread-safe collection of tcp connections keyed by name). – Evk Dec 19 '22 at 08:14
  • @Evk: thanks for your remark. I was thinking of a singleton collection of TCP connection manager objects (the collection being created as a singleton), hence this question. – Dominique Dec 19 '22 at 08:18

0 Answers0