What is private constructor?why we use private constructor?
c#
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Yadagiri ReddyRank #773 · 3K reputationPosted Oct 27, 2014, 11:43 AM EDT
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter();
// Error
Counter.currentCount = 100;
Counter.IncrementCount();
Console.WriteLine("New count: {0}", Counter.currentCount); // Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey(); } } // Output: New count: 101
Ajay YadavRank #313 · 8.1K reputationPosted Oct 27, 2014, 6:04 PM EDT
Private Constructor are those which has static fields. You create a static constructor to initialized static fields. Static constructors are not called explicitly with the new statement. They are called when the class is first referenced. There are some limitation of the static constructor as following;
· Static constructors are parameterless.
· Static constructors can't be overloaded.
· There is none of accessibility of Static constructors.
Arunava BhattacharjeeRank #635 · 3.8K reputationPosted Oct 27, 2014, 7:33 PM EDT
Later C#, we actually don't use private constructors often. Rather, we chose "static" class which eventually serve the same purpose.With a Static Class you no longer had to write a Private Constructor, didn't need to mark them 'Sealed, etc.
Another tendency is to use Singleton pattern. Read it more about this design pattern from Google. But I really never used this pattern in my coding life time, so can't really tell about this.
Hope this helps. Mark the answer as accepted if you are satisfied :)
MahaRank #2,573 · 543 reputationPosted Oct 28, 2014, 1:14 AM EDT