tags:

views:

1289

answers:

4

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?

+7  A: 

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.

Alan
There actually is something special in the IL. Static classes are marked both abstract and sealed (which cannot be otherwise done from C#) which absolutely prevents instantiation.
Greg Beech
+3  A: 

A static class can never be instantiated. No way, no how.

A non-static class with a private constructor but all static methods can be abused in various ways - inheritance, reflection, call the private constructor in a static factory - to instantiate the class.

If you never want instantiation, I'd go with the static class.

Corbin March
+7  A: 

In addition to the previous answers: The compiler won't allow non-static members on static classes and produces and error. This may help a little bit to not accidently add non-static members.

Martin
+1  A: 

Also I'm going to go with the private constructor never being called by the static methods. So any initialisation in there would be wasted... But that's just a theory.

Massif