what is private constructor?why we use private constructor?
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.
MahaPosted Oct 28, 2014, 5:14 AM
Arunava BhattacharjeePosted Oct 27, 2014, 11:33 PM
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 :)
Ajay YadavPosted Oct 27, 2014, 10:04 PM
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.
Yadagiri ReddyPosted Oct 27, 2014, 3:43 PM
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