Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Class Vs. Class with private constructor and all static properties and methods?

Tags:

When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class?

like image 225
Micah Avatar asked Nov 27 '08 05:11

Micah


People also ask

Can static class have private constructor?

You can't get an instance of a static class while you can get instances of a class having private constructor via static methods. Private constructor is used, for instance, in the Singleton design pattern (see, for istance "Implementing Singleton in C#"[^]).

What is the difference between static and private constructor?

Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.

Can static class have static constructor?

They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.

Can a class have both static and non-static constructor?

Yes Normal class can have static constructor but only one. it automatically called only once when any of class member is first time called or access.. even at instance creation. And important thing is static constructor should be parameterless... yes we can have static constructor inside a non-static class.


1 Answers

Static classes are automatically sealed, so people can't inherit and override their behavior.

That is the only real difference (unless there is something special in the IL)

So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.

I would add, that defining a class as static, is "self-documenting" code. Users of your library will know that this class should not be instantiated, and only has static values.

like image 137
Alan Avatar answered Oct 07 '22 15:10

Alan