Posts

Showing posts from September, 2009

C# Static Classes are not Real Classes

In C# and in Java, there's a common idiom to provide utility functions as static methods of classes that cannot be instantiated. This stems from the limitation that these languages don't allow the definition of any function outside of a class. This can be seen as an anti-pattern, because what's missing is the ability to declare functions, not only classes; like in C++. The class has to be declared sealed (final in Java) and a private constructor must be created to prevent inadvertent instantiation. public sealed class ConversionUtils { private ConversionUtils {} public static double ConvertTemperature( double fromTemperature, TemperatureUnit fromUnit, TemperatureUnit toUnit) { ... } } In C# 2.0, static classes were introduced to the language. A static class is a special type of class that's annotated with the static modifier and that: can't be instantiated (implicitly abstract) can't be subclassed (implicitly sealed) can