Generic Types and Inheritance
Explore how to use generic types with inheritance in C#. Learn to create child classes that inherit generics, fix generic types in non-generic children, and extend generics with additional type parameters to build flexible and reusable code structures.
We'll cover the following...
Generic types can be inherited, and generic types can inherit from other classes. We will explore several possible scenarios using our generic Holder<T> class for our examples.
First, we define the base class used throughout this lesson.
Line 3: We define a generic class
Holder<T>with a primary constructor that accepts an integer size.Line 5: We initialize the
Itemsarray property using the size provided in the constructor.Lines 7-10: We override the
ToStringmethod to return a formatted string of all items in the array usingstring.Join.
Same-type inheritance
We can create child classes that inherit the same type parameters as their ancestor. This allows us to extend the functionality of a generic class while keeping it generic.
In ...