What is a "static" class?

Jeremy H picture Jeremy H · Mar 29, 2009 · Viewed 32.9k times · Source

In C# what is the difference between:

public static class ClassName {}

And:

public class ClassName {}

Answer

Jon Skeet picture Jon Skeet · Mar 29, 2009

Firstly, a comment on an answer asked about what "static" means. In C# terms, "static" means "relating to the type itself, rather than an instance of the type." You access a static member (from another type) using the type name instead of a reference or a value. For example:

// Static method, so called using type name
Guid someGuid = Guid.NewGuid();
// Instance method, called on a value
string asString = someGuid.ToString();

Now, static classes...

Static classes are usually used as "utility" classes. The canonical example is probably System.Math. It doesn't make sense to create an instance of math - it just "is". A few rules (both "can" and "can't"):

  • Static classes always derive from object. You can't specify a different base type, or make the static class implement an interface.
  • Static classes can't have any instance members - all variables, methods etc must be static.
  • Static classes can't declare any instance constructors and the compiler doesn't create a parameterless constructor by default. (Before static classes came in C# 2.0, people would often create an abstract class with a private constructor, which prevented instantiation. No need here.)
  • Static classes are implicitly abstract (i.e. they're compiled to IL which describes an abstract class) but you can't add the abstract modifier yourself.
  • Static classes are implicitly sealed (i.e. they're compiled to IL which describes an sealed class) but you can't add the sealed modifier yourself.
  • Static classes may be generic.
  • Static classes may be nested, in either non-static or static classes.
  • Static classes may have nested types, either non-static or static.
  • Only static, top-level non-generic classes can contain extension methods (C# 3.0).