Prerequisite: Constructors in C#
Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members. The private constructor is always declared by using a private
keyword.
Key Points
- It is the implementation of a singleton class pattern.
- Use private constructor when class have only static members.
- Using private constructor, prevents the creation of the instances of that class.
- If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor.
- If a class contains only private constructors and does not contain public constructor, then other classes are not allowed to create instances of that class except nested class.
Syntax :
private constructor_name
{ // Code }
Note:
If we don’t use any access modifier to define a constructor, then the compiler takes that constructor as a public.
Example 1:
C#
using System;
public class Geeks {
private Geeks()
{
Console.WriteLine( "Private Constructor" );
}
}
class GFG {
static void Main() {
Geeks obj = new Geeks();
}
}
|
Compile-time Error:
prog.cs(40, 13): error CS0122: `Geeks.Geeks()’ is inaccessible due to its protection level
Explanation:
In the above example, we have a class named as Geeks. Geeks class contains the private constructor, i.e.
private Geeks()
. In the Main method, when we are trying to access private constructor using this statement
Geeks obj = new Geeks();
, the compiler will give an error because the constructor is inaccessible.
Example 2:
C#
using System;
class Geeks {
public static string name;
public static int num;
private Geeks() {
Console.WriteLine( "Welcome to Private Constructor" );
}
public Geeks( string a, int b) {
name = a;
num = b;
}
}
class GFG {
static void Main() {
Geeks obj2 = new Geeks( "Ankita" , 2);
Console.WriteLine(Geeks.name + ", " + Geeks.num);
}
}
|
Output:
Ankita, 2
Explanation:
The above example contains a class named as Geeks. This Geeks class contains two static variables, i.e. name, and num and two constructors one is a private constructor, i.e. private Geeks()
and another one is default constructor with two parameters, i.e. public Geeks(string a, int b)
. In the Main method, when we try to invoke private constructor using this statement Geeks obj1 = new Geeks();
will give an error because the private constructor does not allow to create instances of Geeks class. The only default constructor will invoke.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Sep, 2023
Like Article
Save Article