C# Tutorial - 19 - Abstract

Uploaded by ProgrammingVideos on 14.01.2010

Declaring a class as abstract means that the class can contain incomplete members that
must be implemented in deriving classes. The abstract class can therefore in addition to
normal class members also contain abstract members. Any member that requires a method
body can be declared as abstract - such as methods, properties, and indexers. These members
are then left unimplemented and only specify their signature while their body is replaced
by a semicolon. To show an example we'll use two abstract methods - GetArea and GetPerimiter.
When we now create a class that derives from this abstract class it is then forced to override
all of the abstract members. If we wanted the override to be optional we would use the
virtual modifier instead. The deriving class can be declared abstract as well, in which
case it does not have to implement any of the abstract members. An abstract class can
also inherit from a non-abstract class. If the base class then has virtual members we
can override these as abstract to force further deriving classes to provide new implementations
for them.
An abstract class cannot be instanced, but we can use it to encapsulate derived classes.
Still, an abstract class can have constructors that we can call from a derived class using
the base keyword.
If we compare abstract classes to interfaces we find that they are similar in many ways.
They can both define member signatures that deriving classes must implement and neither
one of them can be instantiated. The key differences are first that the abstract class can contain
non-abstract members while the interface cannot. And second that a class can implement any
number of interfaces but only inherit from one class, abstract or not.