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

When I create utility classes, I usually create a class that has a private constructor and exposes all its methods and properties as static. What is the best approach for this? What is the difference between how I do this or create a static class?

+20
c #
Nov 27 '08 at 5:46
source share
5 answers

Static classes are automatically sealed, so people cannot inherit and override their behavior.

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

So, if you use a static class, you eliminate the need to make the constructor private and declare the class private.

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 created and has only static values.

+23
Nov 27 '08 at 5:54
source share

A static class can never be created. No way, no.

A non-static class with a private constructor, but all static methods can be used in various ways - inheritance, reflection, calling a private constructor in a static factory - to create an instance of the class.

If you never want to instantiate, I would go with a static class.




Edit - Refinement for FosterZ comment

Say you have this utility class:

public class Utility { public static string Config1 { get { return "Fourty Two"; } } public static int Negate(int x) { return -x; } private Utility() { } } 

If another developer is not aware of his intention, he can do this:

 public class Utility { public static string Config1 { get { return "Fourty Two"; } } public int Config2 { get; set; } public static int Negate(int x) { return -x; } private Utility() { } /// Get an instance of Utility public static Utility GetUtility() { return new Utility(); } } 

You now have a Frankenstein class. Some of its functions require instantiation, and some do not. Maybe this is what you want, but maybe not. You can prevent this from looking at the code, but why not make your intentions explicit in the code? Marking the class as static eliminates any possible confusion. You cannot create a static class or inherit it.

+17
Nov 27 '08 at 5:55
source share

In addition to the previous answers: the compiler does not allow non-static members in static classes, and also creates errors and errors. This can help a little accidentally add non-static elements.

+15
Nov 27 '08 at 5:57
source share

you can pass a class object that has a private constructor as a parameter to any method, but you cannot do the same with a static class. This is the main difference.

+3
Jan 18 '13 at
source share

Also I'm going to go with a private constructor that is never called by static methods. Therefore, any initialization there will be wasted ... But this is just a theory.

+1
Nov 27 '08 at 9:15
source share



All Articles