Abstract Classes in C#

The abstract keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual. For more information, see How to: Define Abstract Properties (C# Programming Guide).

Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. For example:

C#
public abstract class A
{
// Class members here.
}

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:

C#
public abstract class A
{
public abstract void DoWork(int i);
}

Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. For example:

C#
// compile with: /target:library
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}

public abstract class E : D
{
public abstract override void DoWork(int i);
}

public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}

If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

0 Response to "Abstract Classes in C#"