Tuesday, May 13, 2008

Static Classes in C#

When you create methods that do not require access to any instance variables, you would turn it into a static method. If you've got a class with only static methods, it would be easier for other developers to tell right away that the class was never meant to be instantiated - this is done by marking the class as static. Static classes cannot have a non-static constructor and cannot contain any non-static methods. They are also sealed (implicitly) and therefore cannot be inherited.

An alternative to using static classes is to create a private constructor, although this doesn't prevent you from declaring non-static methods with the class.

No comments: