Understanding Generics—Creating Generic Base Classes
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Creating Generic Base Classes
Before we examine generic interfaces, it is worth pointing out that generic classes can be the base class to other classes, and can therefore define any number of virtual or abstract methods. However, the derived types must abide by a few rules to ensure that the nature of the generic abstraction flows through. First of all, if a nongeneric class extends a generic class, the derived class must specify a type parameter:
// Assume you have created a custom // generic list class. public class MyList<T> { private List<T> listOfData = new List<T>(); } // Concrete types must specify the type // parameter when deriving from a // generic base class. public class MyStringList : MyList<string> {}
Furthermore, if the generic base class defines generic virtual or abstract methods, the derived type must override the generic methods using the specified type parameter:
// A generic class with a virtual method. public class MyList<T> { private List<T> listOfData = new List<T>(); public virtual void PrintList(T data) { } } public class MyStringList : MyList<string> { // Must substitute the type parameter used in the // parent class in derived methods. public override void PrintList(string data) { } }
If the derived type is generic as well, the child class can (optionally) reuse the type placeholder in its definition. Be aware, however, that any constraints placed on the base class must be honored by the derived type, for example:
// Note that we now have a default constructor constraint. public class MyList<T> where T : new() { private List<T> listOfData = new List<T>(); public virtual void PrintList(T data) { } } // Derived type must honor constraints. public class MyReadOnlyList<T> : MyList<T> where T : new() { public override void PrintList(T data) { } }
Now, unless you plan to build your own generics library, the chances that you will need to build generic class hierarchies are slim to none. Nevertheless, C# does support generic inheritance.
|

