Last Updated: February 25, 2016
·
1.096K
· edmondo1984

Sealed class hierarchies in C#

A recent post of mine on Stackoverflow has received a lot of attention by the community. I asked how to implement in C# something I learnt in Scala.

Why sealed class hierarchies?

This pattern becomes useful when you are designing a library for third-party use. You want to encode a strategy pattern where the number of options is limited. Certainly, you have enums in C# but enums cannot contain code

public interface IService
 {
     int DoSomething();
 }

 public abstract class ServiceProvider
 {
     public abstract IService GetService();
 }

 public class ServiceConsumer
 {
     public int Consume(ServiceProviderserviceFactory)
     {
         return serviceFactory.GetService().DoSomething();
     }
 }

Why would you make ServiceProvider an abstract class? The crucial point here is that you want to make available only a limited number of Service Providers. If you make it an interface, everybody could implement it

There are two approaches you can use:

  • Make the abstract class constructor private and implement the providers as nested classes
  • Make the abstract class constructor internal, and implement the providers in the same assembly

For example, I really like the following:

public abstract class ServiceProvider
   {
       public abstract IService GetService();

       private ServiceProvider()
       {
       }

       public class CreateNewServiceProvider:ServiceProvider{
           public override IService GetService()
           {
               throw new NotImplementedException();
           }
       }

   }