4.2. Inheritance
Generic concepts, of course, are not constrained to a single class declaration. The type parameters that are supplied with a generic class declaration can also be applied to all the objects that participate in an object hierarchy. Here's a simple example that creates a generic base class and subclasses it with another generic class:
[VB code] Public Class MyBaseClass(Of U) Private _parentData As U Public Sub New() ... End Sub Public Sub New(ByVal val As U) Me._parentData = val End Sub End Class Public Class MySubClass(Of T, U) Inherits MyBaseClass(Of U) Private _myData As T Public Sub New() ... End Sub Public Sub New(ByVal val1 As T, ByVal val2 As U) MyBase.New(val2) Me._myData = val1 End Sub End Class [C# code] public class MyBaseClass<U> { private U _parentData; public MyBaseClass() {} public MyBaseClass(U val) { this._parentData = val; } } public class MySubClass<T, U> : MyBaseClass<U> { private T _myData; public MySubClass() {} public MySubClass(T val1, U val2) : base(val2) { this._myData = val1; } }
Notice here that you have MyBaseClass, which accepts a single type parameter. Then, you subclass MyBaseClass with MySubClass, which accepts two type parameters. The key bit of syntax to notice here is that one of the type parameters used in the declaration of MySubClass was also referenced in the declaration of the parent class, MyBaseClass.
Although this example simply passed the type parameters from the subclass to the base class, you can also use type arguments ...
Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.