CSharp - Private constructor vs sealed class

Introduction

To prevent inheritance, we can use the following two techniques:

Case 1:

class A1
{
          private A1() { }
}

Case 2:

sealed class A2
{
            //some code..
}

In case 1, we can add another constructor and then we can derive a new class from it.

In case 2, we cannot derive a child class.

Demo

using System;

class A1/*from w  w w.  j a  v a 2 s  . c  o m*/
{
    public int x;
    private A1() { }
    public A1(int x) { this.x = x; }
}
sealed class A2
{
    //some code..
}
class B1 : A1
{
    public int y;
    public B1(int x, int y) : base(x)
    {
        this.y = y;
    }
}
//class B2 : A2 { }//Cannot derive from sealed type 'A2'

class Program
{
    static void Main(string[] args)
    {
        B1 obB1 = new B1(2, 3);
        Console.WriteLine("\t x={0}", obB1.x);
        Console.WriteLine("\t y={0}", obB1.y);
    }
}

Result

Analysis

We can see that we can extend the class in case 1.

The private constructors are used in the classes that contain only static members.

We can use private constructors for a singleton design pattern to stop additional instantiation.

Related Topic