In C#, a Private Constructor is created using the Private Access Specifier. If a class contains only a private constructor and lacks any additional Public Constructors, it becomes impossible to instantiate an object for that class externally. Nevertheless, it remains feasible to instantiate objects for the classes internally within the same class.
Constraints like those governing object creation and member access are crucial considerations when attempting to instantiate objects and access members externally from the class.
Creating an Object in C# Using a Private Constructor Inside the Same Class:
An object cannot be instantiated externally from the class; however, it can be instantiated internally within the class. Refer to the following example for clarification. We have declared the private constructor within the Program class, and the Main method is also present within the same Program class. In this scenario, we are instantiating an object of the Program class and executing Method1 within the Main method.
Filename: Constructor.c
using System;
namespace PrivateConstructorDemo
{
class Programs
{
//Private Constructor
private Programs()
{
Console.WriteLine("This shows the Private Constructor");
}
public void Method1()
{
Console.WriteLine("The Method1 is get Called");
}
static void Main(string[] args)
{
//Using the Private Constructor to create an instance of the Program class
Programs ob = new Programs();
ob.Method1();
Console.ReadKey();
}
}
}
Output:
This shows the Private Constructor
The Method1 is get Called
Creating an Instance in C# from Outside the Class
The key point to keep in mind is that the class must contain a public constructor to allow independent instance creation. Whether a class includes a private constructor is irrelevant. However, having a public constructor enables the creation of class instances and the execution of public non-static methods using that constructor.
Examine the illustration provided below to gain a clearer comprehension. The Test class encompasses Private and Public constructors alongside a public function. Subsequently, we instantiate the Test class and execute the Method1 function through the Main function of the Program class (without direct reliance on the Test class).
Example:
using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Using the public Constructor to create an instance of the Test class
Tests obj = new Tests(10);
obj.Method1();
Console.ReadKey();
}
}
public class Tests
{
//the private constructor
private Tests()
{
Console.WriteLine("This is the Private Constructor");
}
//the public constructor with x as parameter
public Tests(int x)
{
Console.WriteLine("Public constructor");
}
public void Method1()
{
Console.WriteLine("The Method1 is get Called");
}
}
}
Output:
Public constructor
The Method1 is get Called
If a class omits a public constructor and includes only a private constructor, it becomes impossible to instantiate the class from outside. This can be illustrated by the following example. In the Test class, there is solely a private constructor. Any attempt to instantiate the Test class from the Main method using this private constructor will result in a compile-time error.
Example:
using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//creating an object using the public constructor
Tests obj = new Tests();
obj.Method1();
Console.ReadKey();
}
}
public class Tests
{
private Tests()
{
Console.WriteLine("This is Private Constructor");
}
public void Method1()
{
Console.WriteLine("the Method1 is Called");
}
}
}
Output:
prog.cs(9,25): error CS0122: `PrivateConstructorDemo.Tests.Tests()' is inaccessible due to its protection level
prog.cs(17,17): (Location of the symbol related to previous error)
Compilation failed: 1 error(s), 0 warnings
Explanation:
We are receiving a notification stating that 'Test.Tests' is not accessible due to its access level, which is in line with the fact that the constructor of the Tests class within the Program class is accessible only within the class itself, as it is declared as private.
The initial point to keep in mind is that a private constructor restricts the instantiation of the class to only the class itself in the absence of a public constructor. If a public constructor is present, it allows for the creation of a new instance outside the class. There are no constraints on creating an instance within the same class.
Use Case: To prevent external instantiation of the class, substitute any public constructors with a private constructor within the class.
Private Constructor Restricting Inheritance in C#:
It signifies that a class is unable to be inherited if it contains a private constructor. This statement is only partly accurate. Now, let's illustrate this with a couple of instances.
It is possible to derive a class when it contains a private constructor alongside any other constructor that is public. The subclass must possess a constructor that is accessible to establish an inheritance relationship. In essence, regardless of the presence of a private constructor in the class, inheritance is feasible as long as there is a public constructor.
Within the Parent class, there are two constructors available for creating objects, namely a private constructor and a public constructor.
Example:
using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
// Creating an instance for the Child class
Child_class obj = new Child_class();
Console.ReadKey();
}
}
public class Parent_class
{
// The private constructor
private Parent_class()
{
Console.WriteLine("The Private constructor of the parent class");
}
// The public constructor
public Parent_class(string Message)
{
Console.WriteLine("The Public constructor of the parent class");
}
}
public class Child_class : Parent_class
{
public Child_class() : base("Hello")
{
Console.WriteLine("The Public constructor of the child class");
}
}
}
Output:
The Public constructor of the parent class
The Public constructor of the child class