Understand Private Constructor And Static Class in C#. NET.
This email we have received from one of our friends where he was asked confusing questions around C# private constructors and static classes. In case you are new to C# private constructors please see this video on C# private constructors.
- If both static and private constructor are meant to be used "to share common data among classes". then what is the difference between these two.
- If class with private constructor and sealed class cannot be inherited , then what is the use of class which cannot be inherited.
- Also sealed class cannot be inherited. then where to use sealed and where to use private constructor (as both class cannot be inherited).
- How can you ensure that only one instance of a C# application is running.
You are right if you are making class static then private constructor is of no use. Actually in .NET 1.X there was no static classes so developer used to use private constructor to prevent object creations.
That means the developer wants to create a strict singleton class which can not be inherited further. And as said previously private constructor can be excused as we have static classes now. So private constructor + sealed means pure static class.
Personally Private constructors i will not use now and would prefer using static keyword. Sealed I will used to prevent further inheritance.
You can use get process, see this video which demonstrates the same in more detail :-