-1

use of private constructor : it cant able to create instance, it cant be inherit, it contain only static data members

without private constructor also i can able to access class with its static declaration and static data member when assign value like the below example

class Test
{        
    public static int x = 12;
    public static int method()
    {
        return 13;
    }
}
class Program
{
    int resut1 = Test.x;
    int resut2 = Test.method();
    static void Main(string[] args)
    {
    }
}

so i have doubts as below why should go to private constructor what is the use of private constructor block is we cant do anything inside of private constructor block when it execute please explain clearly

thanks in advance

Raji
  • 1
  • 1
  • 2
    You can still call it from inside the class. – SLaks Mar 16 '18 at 16:36
  • It seems like your `Test` class should be `static`. I'm not clear where a private constructor comes into play in your example. – juharr Mar 16 '18 at 16:40
  • Already answered with this post: https://stackoverflow.com/questions/2062560/what-is-the-use-of-making-constructor-private-in-a-class – Fancy5g Mar 16 '18 at 16:40
  • i compared this with private constructor what it create more. – Raji Mar 16 '18 at 16:42

2 Answers2

-1

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. For more information see Static Classes and Static Class Members.

Follow this https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors

-2

A private constructor prevents the generic default constructor from being used.

The generic default constructor allows a class to be instantiated; while, a private constructor.

According to this microsoft doc, they are generally used to prevent people from instantiating classes that only have static members/functions.

Tyler
  • 957
  • 11
  • 27