Sunday, June 15, 2008

Best Practices(Class Modifiers in C# .NET)

Every class modifiers has a purpose. One of the best practices is to use appropriate modifiers to meet those purposes.

Abstract

The purpose of making a class abstract is to generalize classes on some common criteria but to prevent from creating instance. Class declared as abstract, it cannot be newed. An abstract class can be derived from another class, it can implement interfaces, and other class can be derived from the abstract class and make the abstract members concrete. If anyone wants to build a class which should not be instantiate but should be sub-classed, the class should be defined as abstract.

Sealed

The purpose of making a class sealed is to prevent inheritance. A sealed class can be derived from another class but cannot be inherited by other classes. If anyone wants to make a class which should not be further subclassed, the class should be declared sealed.


Static

The purpose of making a static class is to prevent both instantiation and inheritance. Usually utiliy classes are made static. static classes are sealed by default. They cannot inherite any class except System.Object and cannot implement any interfaces.

No comments: