April 5, 2009 21:40
Salutary static adjunct for class declarations was introduced in C#2, aimed to solve the whole bunch of issues.
Previously, in order to set up a container of static methods you had to do some tricks while declaring that class.
- First off, since it's useless to create an instance of such a class, you would create a private constructor that could never be called from the outside.
- Then you would mark the class sealed so that nobody could inherit from it.
-
And then you would start adding your static methods, properties, etc.
Apparently there are few problems with this approach.
- The private constructor takes up space in the IL and metadata (not a big deal but anyway).
- If you forgot to mark the class sealed, you could derive from it.
- There's no protection against having an instance method in such a class.
You may think those are minor problems but they're not. For our edification and delight, there was a bug in .NET 1.0 in Environment class that had a property that wasn't static. As it was an instance member on a class that could never be instantiated, no one could call it. The problem wasn’t discovered early enough in the product cycle to fix it before the release (!) so .NET 1.0 has a "static" class with an instance property on it.
Starting from C#2 we can mark a class with a static
keyword, which means that it's sealed, has no constructor, and the
compiler will scream an error if you put there an instance method.
Easy-peasy.
As usual, the more is put on the compiler the better off we are.