What is the difference between a class having private constructor and a sealed class having private constructor?

jannagy02 picture jannagy02 · May 19, 2013 · Viewed 17.5k times · Source

Is there any difference between A and B?

Class A has private constructor:

class A
{
    private A()
    { }
}

Class B is sealed and has a private constructor:

sealed class B
{
    private B()
    { }
}

Answer

Mike Zboray picture Mike Zboray · May 19, 2013

Yes A can be inherited by a nested class, while B cannot be inherited at all. This is perfectly legal:

public class A {
  private A() { }

  public class Derived : A { }
}

Note that any code could create a new A.Derived() or inherit from A.Derived (its constructor is public), but no other classes outside the source text of A can inherit directly from A.

A typical use for something like this is a class with enum-like values but which can have custom behavior:

public abstract class A {
  private A() { }

  public abstract void DoSomething();

  private class OneImpl : A { 
    public override void DoSomething() { Console.WriteLine("One"); }
  }

  private class TwoImpl : A { 
    public override void DoSomething() { Console.WriteLine("Two"); }
  }

  public static readonly A One = new OneImpl();
  public static readonly A Two = new TwoImpl();
}