.NET Type Design Guidelines—Static Class Design


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

.NET Type Design Guidelines

© 2006 Microsoft Corp.

Static Class Design

A static class is defined as a class that contains only static members (of course besides the instance members inherited from System.Object and possibly a private constructor). Some languages provide built-in support for static classes. In C# 2.0, when a class is declared to be static, it is sealed, abstract, and no instance members can be overridden or declared.

public static class File {
   ...
}

If your language does not have built-in support for static classes, you can declare such classes manually as in the following C++ example:

public class File abstract sealed {
   ...
}

Static classes are a compromise between pure object-oriented design and simplicity. They are commonly used to provide shortcuts to other operations (such as System.IO.File), or functionality for which a full object-oriented wrapper is unwarranted (such as System.Environment).

DO use static classes sparingly.
Static classes should be used only as supporting classes for the object-oriented core of the framework.
DO NOT treat static classes as a miscellaneous bucket.
There should be a clear charter for the class.
DO NOT declare or override instance members in static classes.
DO declare static classes as sealed, abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes.
BRIAN GRUNKEMEYER
In the .NET Framework 1.0, I wrote the code for the System.Environment class, which is an excellent example of a static class. I messed up and accidentally added a property to this class that wasn't static (HasShutdownStarted). Because it was an instance method on a class that could never be instantiated, no one could call it. We didn't discover the problem early enough in the product cycle to fix it before releasing version 1.0.

If I were inventing a new language, I would explicitly add the concept of a static class into the language to help people avoid falling into this trap. And in fact, in C# 2.0 did add support for static classes!

JEFFREY RICHTER
Make sure that you do not attempt to define a static structure, because structures (value types) can always be instantiated no matter what. Only classes can be static.


Previous_Page_.gif Next_Page_.gif





Personal tools