Tuesday, May 22, 2007

Static Classes in .NET 2.0

We all use static methods while writing utility classes. The utility methods which we commonly use are Console.WriteLine(), MessageBox.Show() and Math library functions. In .NET v1.1 we can mark a method as a static method so that the method can be accessed using the class reference. As a class can have a mixture of static and non static methods, sometimes this caused problem to the designers with the challenges of educating developers not club static and non static methods in a single class. .NET 2.0 introduced static classes which brings many facilities and solves many of the design problems. Static classes are used when a class needs to contain only static methods and attributes which are not specific to any unique instance. The following are the features of static classes

  • A static class should only static members (functions, properties, etc). No non static members are allowed inside the class definition
  • Static classes cannot be instantiated. So, there are no special measures(like creating private constructors) needs to be take care in the design to disallow object creation.
  • Static classes are sealed so they cannot be inherited.
  • Static classes can only have static constructor to initialize static members.