1. Back To Blog

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.

 

  1. 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.
  2.  

    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.

     

  3. If class with private constructor and sealed class cannot be inherited , then what is the use of class which cannot be inherited.
  4.  

    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.

     

  5. Also sealed class cannot be inherited. then where to use sealed and where to use private constructor (as both class cannot be inherited).
  6.  

    Personally Private constructors i will not use now and would prefer using static keyword. Sealed I will used to prevent further inheritance.

     

  7. How can you ensure that only one instance of a C# application is running.
  8.  

    You can use get process, see this video which demonstrates the same in more detail :-

     

    Shiv Prasad Koirala

    Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social