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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rajeev KumarPosted Feb 27, 2023, 6:07 AM
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
Kunal VaishyaPosted Oct 9, 2012, 1:51 AM
Sandeep Singh ShekhawatPosted Oct 9, 2012, 1:32 AM
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
Santhosh Kumar JayaramanPosted Oct 9, 2012, 1:27 AM
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