Search⌘ K
AI Features

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.

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.

C# 14.0
namespace GenericTypes;
public class Holder<T>(int holderSize)
{
public T[] Items { get; private set; } = new T[holderSize];
public override string ToString()
{
return "Items inside: " + string.Join(" ", Items);
}
}
  • Line 3: We define a generic class Holder<T> with a primary constructor that accepts an integer size.

  • Line 5: We initialize the Items array property using the size provided in the constructor.

  • Lines 7-10: We override the ToString method to return a formatted string of all items in the array using string.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 ...