Chapter 6 discussed how one class can reference other classes via fields and properties. This chapter discusses how to use the inheritance relationship between classes to build class hierarchies that form an “is a” relationship.
It is common to want to extend a given type to add features, such as behavior and data. The purpose of inheritance is to do exactly that. Given a Person class, you create an Employee class that additionally contains EmployeeId and Department properties. The reverse approach may also be applied. Given, for example, a Contact class within a personal digital assistant (PDA), you may decide to add calendaring support. Toward this effort, you create an Appointment class. However, instead of redefining the methods and properties that are common to both classes, you might choose to refactor the Contact class. Specifically, you could move the common methods and properties for Contact into a base class called PdaItem from which both Contact and Appointment derive, as shown in Figure 7.1.
The common items in this case are Created, LastUpdated, Name, ObjectKey, and the like. Through derivation, the methods defined on the base class, PdaItem, are accessible from all classes derived from PdaItem.
When declaring a derived class, follow the class identifier with a colon and then the base class, as Listing 7.1 demonstrates.
Listing 7.2 shows how to access the properties defined in Contact.
Even though Contact does not directly have a property called Name, all instances of Contact can still access the Name property from PdaItem and use it as though it was part of Contact. Furthermore, any additional classes that derive from Contact will also inherit the members of PdaItem or any class from which PdaItem was derived. The inheritance chain has no practical limit, and each derived class will have all the members of its base class inheritance chain combined (see Listing 7.3). In other words, although Customer doesn’t derive from PdaItem directly, it still inherits the members of PdaItem.
In Listing 7.3, PdaItem is shown explicitly to derive from object. Although C# allows such syntax, it is unnecessary because all classes that don’t have some other derivation will derive from object, regardless of whether it is specified.
As Listing 7.4 shows, because derivation forms an “is a” relationship, a derived type value can always be directly assigned to a base type variable.
The derived type, Contact, is a PdaItem and can be assigned directly to a variable of type PdaItem. This is known as an implicit conversion because no cast operator is required and the conversion will, in principle, always succeed; that is, it will not throw an exception.
The reverse, however, is not true. A PdaItem is not necessarily a Contact; it could be an Appointment or some other derived type. Therefore, casting from the base type to the derived type requires an explicit cast, which could fail at runtime. To perform an explicit cast, you identify the target type within parentheses prior to the original reference, as Listing 7.4 demonstrates.
With the explicit cast, the programmer essentially communicates to the compiler to trust her—she knows what she is doing—and the C# compiler allows the conversion to proceed if the target type is derived from the originating type. Although the C# compiler allows an explicit conversion at compile time between potentially compatible types, the Common Language Runtime (CLR) will still verify the explicit cast at execution time, throwing an exception if the object instance is not actually of the targeted type.
The C# compiler allows use of the cast operator even when the type hierarchy allows an implicit conversion. For example, the assignment from contact to item could use a cast operator as follows:
item = (PdaItem)contact;
or even when no conversion is necessary:
contact = (Contact)contact;
All members of a base class, except for constructors and destructors, are inherited by the derived class. However, just because a member is inherited, that does not mean it is accessible. For example, in Listing 7.6, the private field, _Name, is not available in Contact because private members are accessible only inside the type that declares them.
As part of respecting the principle of encapsulation, derived classes cannot access members declared as private.1 This forces the base class developer to make an explicit choice as to whether a derived class gains access to a member. In this case, the base class is defining an API in which _Name can be changed only via the Name property. That way, if validation is added, the derived class will gain the validation benefit automatically because it was unable to access _Name directly from the start. Regardless of the access modifier, all members can be accessed from the class that defines them.
Encapsulation is finer grained than just public or private, however. It is possible to define members in base classes that only derived classes can access. (Any member can also always access other members within the same type.) As an example, consider the ObjectKey property shown in Listing 7.7.
ObjectKey is defined using the protected access modifier. The result is that it is accessible only outside of PdaItem from members in classes that derive from PdaItem. Because Contact derives from PdaItem, all members of Contact (i.e., Save()) have access to ObjectKey. In contrast, Program does not derive from PdaItem, so using the ObjectKey property within Program results in a compile-time error.
An important subtlety shown in the static Contact.Copy(PdaItem pdaItem) method is worth noting. Developers are often surprised that it is not possible to access the protected ObjectKey of a PdaItem from code within Contact, even though Contact derives from PdaItem. The reason is that a PdaItem could potentially be an Address, and Contact should not be able to access protected members of Address. Therefore, encapsulation prevents Contact from potentially modifying the ObjectKey of an Address. A successful cast of PdaItem to Contact will bypass this restriction (i.e., ((Contact)pdaItem).ObjectKey), as does accessing contact.ObjectKey. The governing rule is that accessing a protected member from a derived class requires a compile-time determination that the protected member is an instance of the derived class.
Extension methods are technically not members of the type they extend and, therefore, are not inherited. Nevertheless, because every derived class may be used as an instance of any of its base classes, an extension method for one type also extends every derived type. In other words, if we extend a base class such as PdaItem, all the extension methods will also be available in the derived classes. However, as with all extension methods, priority is given to instance methods. If a compatible signature appears anywhere within the inheritance chain, it will take precedence over an extension method.
Requiring extension methods for base types is rare. As with extension methods in general, if the base type’s code is available, it is preferable to modify the base type directly. Even in cases where the base type’s code is unavailable, programmers should consider whether to add extension methods to an interface that the base type or the individual derived types implement. We cover interfaces and their use with extension methods in Chapter 8.
In theory, you can place an unlimited number of classes in an inheritance tree. For example, Customer derives from Contact, which derives from PdaItem, which derives from object. However, C# is a single-inheritance programming language (as is the Common Intermediate Language [CIL] to which C# compiles). Consequently, a class cannot derive from two classes directly. It is not possible, for example, to have Contact derive from both PdaItem and Person.
C#’s single inheritance is one of its major object-oriented differences from C++.
For the rare cases that require a multiple-inheritance class structure, one solution is to use aggregation; instead of one class inheriting from another, one class contains an instance of the other. C# 8.0 provides additional constructs for achieving this, so we defer the details of implementing aggregation until Chapter 8.
Designing a class correctly so that others can extend it via derivation can be a tricky task that requires testing with examples to verify the derivation will work successfully. Listing 7.8 shows how to avoid unexpected derivation scenarios and problems by marking classes as sealed.
Sealed classes include the sealed modifier, so they cannot be derived from. The string type is an example of a type that uses the sealed modifier to prevent derivation.