This post originated from an RSS feed registered with .NET Buzz
by Eric Gunnerson.
Original Post: C# Whidbey Featurette #3: Static classes
Feed Title: Eric Gunnerson's C# Compendium
Feed URL: /msdnerror.htm?aspxerrorpath=/ericgu/Rss.aspx
Feed Description: Eric comments on C#, programming and dotnet in general, and the aerodynamic characteristics of the red-nosed flying squirrel of the Lesser Antilles
Because all functions in C# must live inside of a class, there are some clases - System.Math is a canonical example - that are merely collections of static methods. Since it's useless to create an instance of such a class, in current versions of C#, you can protect against this by creating a private constructor. The constructor can never be called, and therefore no instance can be created.
There are three issues with this approach:
The private constructor takes up space in the IL, metadata, etc. This isn't a big deal, but it does have a tiny effect.
It's not clear from casual inspection of the source that this class only has static methods.
There's no protection against instance methods on static classes. The compiler will happily let you write methods that could never be called (in theory, a static could call a private constructor and return the instance, but not in this scenario)
You could derive from the class if you forgot to mark it sealed
So, for Whidbey, we allow the user to mark a class as static, which means that it's sealed, has no constructor, and the compiler will give you an error if you write an instance method.
Rumor has it that the 1.0 frameworks shipped with an instance method on a static class.