Wikibooksβ

C# Programming/Abstract classes

In general terms, an interface is the set of public members of a component. Of course, this is also true for C# interface. A C# class also defines an interface, as it has a set of public members. A non-abstract C# class defines the implementation of each member.

In C#, it is possible to have a type that is intermediate between a pure interface that does not define any implementation, and a type that defines a complete implementation. This is called an abstract class and is defined by including the abstract keyword in the class definition.

An abstract class is somewhere between a C# interface and a non-abstract class. Of the public members defined by an abstract class, any number of those members may include an implementation.

For example, an abstract class might provide an implementation for none of its members.

Although an abstract class is similar to a non-abstract class, some important differences exist. For one thing, you cannot create an instance of an abstract class with the new keyword. For example, the following statement will raise a compiler error:

AbstractShapeshape=newAbstractShape();

Of course, assuming the concrete class Square derives from AbstractShape, the following would be correct:

AbstractShapeshape=newSquare();

A second difference is that an abstract class may have abstract members. As was shown above, this is not a must. To create a class with at least one abstract member, the abstract keyword must be added before the class keyword.

The third difference is that a class cannot be both abstract and sealed.

Overriding an abstract method is effectively the same as overriding a virtual method - you cannot change the access specifiers (i.e. you can't convert a protected abstract method into public), and you cannot add a missing get or set to an abstract property. The only difference is that "forgetting" the new or override keyword results in an error, if the class this method is belonging to was derived from an abstract class, and it will result in a warning, if the class tries to override a virtual method.