Use of Private Constructor in C#
Why we use Private constructor? How to access the method of Private constructor in 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
Santhosh Kumar JayaramanRank #563 · 4.3K reputationPosted Oct 8, 2012, 9:27 PM EDT
When you want to prevent the users of your class from instantiating the class directly. Some common cases are:
most common example is singleton pattern
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); } } Output 5 6
Check this
http://www.dotnetperls.com/private-constructor
Sandeep Singh ShekhawatRank #147 · 15.6K reputationPosted Oct 8, 2012, 9:32 PM EDT
Private constructor uses when application is using single instance in single session of application means when an user is using an application and want operation from that class which have private constructor multiple times so in all time we will use single instance of that class to perform all operation which are realted to that object.
It defines creational pattern means Singlton pattern for development of application.
For More detail please go through following links:
http://www.c-sharpcorner.com/UploadFile/SukeshMarla/learn-design-pattern-singleton-pattern/
http://www.c-sharpcorner.com/UploadFile/amit.dhania/singleton-pattern/
http://www.c-sharpcorner.com/UploadFile/ff2f08/singleton-design-pattern/
http://www.c-sharpcorner.com/UploadFile/4d790c/singleton-pattern-creational-pattern/
http://www.c-sharpcorner.com/UploadFile/40e97e/singleton-pattern/
http://www.c-sharpcorner.com/uploadfile/ashish_2008/singleton-design-pattern-in-C-Sharp/
Thanks
Sandeep
Kunal VaishyaRank #990 · 2K reputationPosted Oct 8, 2012, 9:51 PM EDT
Rajeev KumarRank #1,334 · 1.3K reputationPosted Feb 27, 2023, 1:07 AM EST
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static. Sealed class cannot be inherited but it can be instantiated. On the other hand, a class having a private constructor neither can be inherited nor instantiated due to its protection level