C# Design Strategies - p-patel/software-engineer-knowledge-base GitHub Wiki

https://app.pluralsight.com/library/courses/csharp-design-strategies/

Singletons

What is a singleton?

  • A class which only allows one instance

Simple version

  • static class - it is sealed, abstract, has no constructor and compiler does not allow variables of static class type
  • fine in the case where class requires no state and has nothing that requires it to be an instance - having just static methods is fine e.g. System.Math class
  • Tip: avoid code that compiles but will never work - catch these errors at compile-time
  • create a private constructor, called by a static public method that returns single static field instance from within the class - however note that this is not thread-safe (as a general rule only make classes than deal with concurrency thread-safe and don't attempt to make any other classes thread-safe).