Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Trying to create a singleton class

Tags:

c#

singleton

I've been reading about how to implement a thread safe singleton class. I've managed to find many different ways of creating one, however I have not managed to find information about where exactly I'm supposed to put my properties and methods etc. in the class.

For example:

public sealed class Singleton
{
   //Do I put properties here?     

   private Singleton() {}

   public static Singleton GetInstance()
   {
      return NestedSingleton.singleton;
   }

   class NestedSingleton
   {
      //Do I put properties here?  
      internal static readonly Singleton singleton = new Singleton();

      static NestedSingleton() {}

      //Do my methods go here
   }

  //or here?
}
like image 308
user9993 Avatar asked May 26 '26 15:05

user9993


2 Answers

The methods would go in the outer class. The only purpose of the nested class is to enforce particular timing of the initialization of the singleton instance of the outer class.

Don't forget that your GetInstance method returns a reference to Singleton - not NestedSingleton. Indeed, NestedSingleton is private, so code outside Singleton doesn't even know about its existence. You might want to make it a static class, too. (That would stop you from even trying to add instance members to it.)

Personally I would only use this form if I wanted really tight control over initialization - normally I'd just use a field in the Singleton class itself. (Or a Lazy<T>...) That's a bit simpler. If you haven't already come across my article on singleton implementations in C#, you might want to have a look at it. (I suspect you've already seen it, but...)

like image 115
Jon Skeet Avatar answered May 30 '26 19:05

Jon Skeet


You should put all instance members in the outer class.

The inner class is a private holder type which only exists to lazily initialize the singleton value.
It should be static.

like image 38
SLaks Avatar answered May 30 '26 18:05

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!