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?
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#"[^]).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With