0

I have found a code snippet that we can use for a singleton instance of a class in C#.

Here is the code:

public sealed class Singleton
{
 private static Singleton instance = null;
 private static readonly object padlock = new object();

 Singleton()
 {
 }

 public static Singleton Instance
 {
  get
  {
   lock (padlock)
  {
   if (instance == null)
   {
    instance = new Singleton();
   }
   return instance;
    }
   }
 }
}

I have to create a generic singleton instance that I can use for any type of class. But that generic method should have one instance for one type.

Rafaqat Ali
  • 676
  • 7
  • 26
  • There's no need to use the locks if you use a static constructor. Refer to [this](https://csharpindepth.com/Articles/Singleton) article. The singleton itself is generic. You can use any type you want for the actual properties. – devsmn Dec 18 '19 at 16:28
  • Adding also this previous post as it seems to answer quite well to your question. Let us know if this is still unclear: [here](https://stackoverflow.com/questions/2319075/generic-singletont) – WilliamW Dec 18 '19 at 16:30
  • Does this answer your question? [Generic Singleton](https://stackoverflow.com/questions/2319075/generic-singletont) – Rafaqat Ali Dec 18 '19 at 16:32

0 Answers0