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

advertisements

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()
    { }
}


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();
}