Click here to Skip to main content
15,889,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C#
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

What I have tried:

i tried without private constructor

in private constructor also not access static data members when call inside of non static methods or inside of class block.

the same as one class (class1 ) have static data members and another class (class2)

class1 static data member cant able to call in class2
Posted
Updated 17-Mar-18 2:59am
v2

1 solution

Private constructors just prevent "outside" classes from creating any instances - they are mostly used for Singleton classes. But that has no effect at all on static items because they do not require an instance to work at all.
So this:
C#
public MyClass
    {
    private MyClass() {}
    public static myProperty { get; set; }
    public static int myMethod( int x) { return x * 2; }
    public MyClass GetInstance() { return new MyClass(); }
    }
myProperty, myMethod, and GetInstance are all accessible by outside code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900