Why are static classes considered “classes” and “reference types”?

Posted by Timwi on Stack Overflow See other posts from Stack Overflow or by Timwi
Published on 2010-05-06T12:38:36Z Indexed on 2010/05/06 12:48 UTC
Read the original article Hit count: 213

Filed under:
|
|
|
|

I’ve been pondering about the C# and CIL type system today and I’ve started to wonder why static classes are considered classes. There are many ways in which they are not really classes:

  • A “normal” class can contain non-static members, a static class can’t. In this respect, a class is more similar to a struct than it is to a static class, and yet structs have a separate name.
  • You can have a reference to an instance of a “normal” class, but not a static class (despite it being considered a “reference type”). In this respect, a class is more similar to an interface than it is to a static class, and yet interfaces have a separate name.
  • The name of a static class can never be used in any place where a type name would normally fit: you can’t declare a variable of this type, you can’t use it as a base type, and you can’t use it as a generic type parameter. In this respect, static classes are somewhat more like namespaces.
  • A “normal” class can implement interfaces. Once again, that makes classes more similar to structs than to static classes.
  • A “normal” class can inherit from another class.

It is also bizarre that static classes are considered to derive from System.Object. Although this allows them to “inherit” the static methods Equals and ReferenceEquals, the purpose of that inheritance is questionable as you would call those methods on object anyway. C# even allows you to specify that useless inheritance explicitly on static classes, but not on interfaces or structs, where the implicit derivation from object and System.ValueType, respectively, actually has a purpose.

Regarding the subset-of-features argument: Static classes have a subset of the features of classes, but they also have a subset of the features of structs. All of the things that make a class distinct from the other kinds of type, do not seem to apply to static classes.

Regarding the typeof argument: Making a static class into a new and different kind of type does not preclude it from being used in typeof.

Given the sheer oddity of static classes, and the scarcity of similarities between them and “normal” classes, shouldn’t they have been made into a separate kind of type instead of a special kind of class?

© Stack Overflow or respective owner

Related posts about c#

Related posts about clr