Private Constructor

A private constructor cannot be externally called. It is used to ensure higher-quality code bases on complex projects. A private constructor forces the class to provide a controlled and unified access pattern.

Example:

Inside the private constructor, a field is initialized to a constant number. The private constructor ensures that it is impossible for the class to be instantiated directly from external classes.


Programe


using System;

public sealed class Test {
	public static readonly Test Instance = new Test();
	// Singleton pattern
	public int A;
	// Instance field
	private Test() // This is the private constructor {
		this.A = 5;
	}
}

class Program {
	static void Main() {
		// We can access an instance of this object that was created.
		// ... The private constructor was used.
		Test test = Test.Instance;
		// These statements show that the class is usable.
		Console.WriteLine(test.A);
		test.A++;
		Console.WriteLine(test.A);
	}
}


Quantitative Aptitude
Reasoning
Programming
Interview