Where this gets more interesting is when your base class is generic class (open or constructed type). For
this scenario, you can still override methods from your generic base class. However, there are some
nuances you must keep in mind. Let's start by looking at the common, simple case:
[VB code]
Public Class MyBaseClass(Of T)
Overridable Sub Foo(ByVal val As T)
Console.WriteLine("In BaseClass")
End Sub
End Class
Public Class MySubClass1(Of T, U)
Inherits MyBaseClass(Of T)
Overrides Sub Foo(ByVal val As T)
Console.WriteLine("In SubClass")
End Sub
End Class
Public Class MySubClass2(Of T, U)
Inherits MyBaseClass(Of Integer)
Overrides Sub Foo(ByVal val As T)
Console.WriteLine("In SubClass")
End Sub
End Class
[C# code]
public class MyBaseClass<T> {
public virtual void Foo(T val) { }
}
public class MySubClass1<T, U> : MyBaseClass<T> {
public override void Foo(T val) { }
}
public class MySubClass2<T, U> : MyBaseClass<int> {
public override void Foo(T val) { }
}
This example declares a generic base class (
MyBaseClass
) that includes one overridable method,
Foo
. It
then implements two generic subclasses that both override the
Foo
method. On the surface, there doesn't
appear to be any issues. Both of these classes provide identical signatures for the method. So, why does
MySubClass2
fail to compile? Well, if you look more closely, you'll notice that
MySubClass2
uses a
constructed type in its inheritance declaration. Meanwhile,
MySubClass1
uses an open type for its
declaration. This one point of difference is crucial. With
MySubClass1
, the type parameter
T
used inher-
itance declaration and the overridden method can be guaranteed to match. That doesn't hold true for
MySubClass2
. The type of
T
can, and likely will, differ from the integer type, which is what is provided
to the parent's
T
type parameter. As you might expect, the compiler is going to detect this and throw an
error during the compilation of
MySubClass2
.
64
Chapter 4
07_559885 ch04.qxd 9/8/05 11:01 PM Page 64