Skip to Content
Programming C# 10
book

Programming C# 10

by Ian Griffiths
August 2022
Intermediate to advanced
833 pages
25h 30m
English
O'Reilly Media, Inc.
Book available
Content preview from Programming C# 10

Chapter 6. Inheritance

C# classes support inheritance, a popular object-oriented code reuse mechanism. When you write a class, you can optionally specify a base class. Your class will derive from this, meaning that everything in the base class will be present in your class, as well as any members you add.

Classes and class-based record types support only single inheritance (so you can only specify one base class). Interfaces offer a form of multiple inheritance. Value types, including record struct types, do not support inheritance at all. One reason for this is that value types are not normally used by reference, which removes one of the main benefits of inheritance: runtime polymorphism. Inheritance is not necessarily incompatible with value-like behavior—some languages manage it—but it often has problems. For example, assigning a value of some derived type into a variable of its base type ends up losing all of the fields that the derived type added, a problem known as slicing. C# sidesteps this by restricting inheritance to reference types. When you assign a variable of some derived type into a variable of a base type, you’re copying a reference, not the object itself, so the object remains intact. Slicing is an issue only if the base class offers a method that clones the object and doesn’t provide a way for derived classes to extend that (or it does, but some derived class fails to extend it).

Classes specify a base class using the syntax shown in Example 6-1—the base type ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming C# 8.0

Programming C# 8.0

Ian Griffiths
Programming C# 12

Programming C# 12

Ian Griffiths

Publisher Resources

ISBN: 9781098117801Errata PageSupplemental Content