Common Type System—Subclassing and Polymorphism


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

Common Type System

© 2006 Wiley Publishing Inc.

Subclassing and Polymorphism

Types can derive from other types, forming a special relationship between two types. We say type B is a subclass of type A if B derives from A. In IL terminology, B extends A. In this example, A is B’s base type (a.k.a. super- or parent type). Types can only have one immediate base type in the CTS; in other words, multiple inheritance is not supported. Interfaces, a topic we discuss in this section, enable multiple interface inheritance, but this is subtly different from what is normally meant as multiple inheritance. Because userdefined structs cannot derive from an arbitrary type (they implicitly derive from System.ValueType and are sealed by default), we just go ahead and say subclass instead of using more precise terminology.

You can express a subtype relation in C# as follows:

class A {}
class B : A {}
class C : A {}

In this example, both B and C are subclasses of A. Of course, we can then go ahead and create additional subclasses of A, or even subclasses of B and C. In IL this looks as follows:

.class private auto ansi beforefieldinit 
   A extends [mscorlib]System.Object {}
.class private auto ansi beforefieldinit
   B extends A {}
.class private auto ansi beforefieldinit
   C extends A {}

When B is a subclass of A, we say that B is polymorphic with respect to A. All this means is that, because A subclass inherits all of the publicly visible traits of its base type, an instance of B can be treated just like an instance of A in a type-safe manner. The reverse is of course not true. We discuss inheritance in more detail shortly.


Previous_Page_.gif Next_Page_.gif





Personal tools