Today, I have been reading about static class and private constructor.
Static Class - We cannot create an instance on the static class. we cannot inherit the static class. Only single instance is generated.
Private Constructor - We cannot create an instance. We cannot inherit. (I Don't know about how many instance is generated.)
I created two console application i.e. One for static Class, One for Private constructor.
Static Class Code
I understood single object in generated as constructor is called once.
Private Constructor Code
Now, I didn't understand that whether any object is generated or not.
I have two question.
Question 1. I didn't find any particular difference between Private constructor and Static class. Can you please suggest me that in which scenario where I should use Private Constructor and where should I use Static class as I can use both of them.
Question 2. If I use private constructor, how many objects is generated?
Thanks.
EDIT :
I think that people didn't understand my question. I know that static constructor always call once on the first reference. Static constructor is used to initialize static members of the class.
Question 1. I have a situation : I need to create a class which cannot be instantiated.I can do this by either static class or private constructor. So my question is that "Is there any difference between both of them? which one I should use??"
Question 2. If I use private constructor, how many object is created? If answer is 0 then how private constructor's memory allocation works in the CLR. There is no memory allocation if I use private constructor.
Private Constructor - We cannot create an instance.
isn't right. Nested classes can – DeedradeedstestPrivateConstructor
can have instances in principle, and values can have typetestPrivateConstructor
. For example you can make a variabletestPrivateConstructor value = null;
, or you can make a method parameterstatic void Consume(testPrivateConstructor value) { Console.WriteLine("The value was: " + value); }
. Those things are disallowed for static classes liketestStaticClass
. And of coursetestPrivateConstructor
can have members (methods, properties, fields, events) that are non-static. – Stan