When to Use Singleton vs Static Class

Tags: Interview Questions, ASP.NET, Design Patterns

Another question that gets asked during interviews is "What is the difference between a static class and a singleton?" or "When would you use a static class vs a singleton?".

Difference

The difference between the two is fairly obvious: a singleton is a software design pattern that limits instantiation of a class to a single instance.  A static class is a language feature (of C#, etc) whereby the class cannot be instantiated.

When to Use

The more interesting part of the discussion is when should you use one over the other.  Here are the significant differences:

  • A singleton class can implement an interface, a static class cannot
  • A singleton instance can be passed to a method, a static class cannot.

Both will generally be created upon use (lazily) and both will hang around until the AppDomain is destroyed.  Neither can be inherited from.  A static class is sealed and a singleton has a private constructor.

So if you need an actual instance of your class and you only want there to be one, use the singleton.  If you want no instances of your class, something more akin to a function type of behavior, then use a static class.  There are lots of these built into .Net like the Math class etc.

When asked this question I will also mention that an IoC container can usually manage singletons for you, so you don't actually need to implement the singleton pattern.  This allows you to mock your "singleton" class for testing.  yippee!

No Comments

Add a Comment