Thursday, March 22, 2018

Singleton Pattern vs. C# Static Class

I ran into an old foe the other day when we were discussing interview questions; which to choose: standard singleton pattern or static class? At the most basic level, both constructs are useful in limiting the number of instances of an object that can be created. There are numerous subtle differences at the implementation level, but the single biggest difference is at an object-oriented level: static classes do not support polymorphism. This stems from a combination of factors at the language level; in short, a static class cannot inherit from a base class (abstract or concrete) nor can it implement any interface methods. Conversely, you can neither define static virtual methods on a class, nor can you define them on an interface. So, if you're ever using dependency injection - a technique that relies heavily on polymorphism - you will likely find that static classes will be inadequate. There are a number of other runtime level differences, but these are all secondary to the polymorphism issue. The simplest is that a static class can never be instantiated, and all methods are executed against the type instance. Contrast this with the singleton, of which exactly one instance is created, and where methods are executed against that instance. Next time I choose, I'm going anti-static for all but the simplest "utility" classes.