5.6. Overriding Generic Methods
Generic methods may also be overridden by descendant classes. In fact, generic methods introduce surprisingly few new facets when it comes when overriding methods. The syntax for overriding generic methods follows the same pattern as non-generic methods where the overriding method must match, precisely, the parameters of the parent method. With a generic method, the only difference is that the parameters can be expressed as type parameters. Here's a simple example:
[VB code] Public Class Person(Of T, U) Public Overridable Sub Foo1(Of I)(ByVal val1 As T) End Sub Public Overridable Sub Foo1(Of I)(ByVal val1 As Int32) End Sub Public Overridable Sub Foo2(Of I, J)(ByVal val1 As U) End Sub Public Overridable Sub Foo3(Of I, U)(ByVal val1 As I, ByVal val2 As U) End Sub Public Overridable Sub Foo4(Of D, E, F)(ByVal val1 As D, ByVal val2 As E) End Sub Public Overridable Function Foo5(Of I As IComparable)(ByVal val1 As I) As I End Function End Class Public Class Employee(Of T, U) Inherits Person(Of String, U) 'Error: can't verify this is unique for all permutations Public Overrides Sub Foo1(Of I)(ByVal val1 As Int32) End Sub Public Overrides Sub Foo2(Of I, J)(ByVal val1 As U) End Sub Public Overrides Sub Foo3(Of I, U)(ByVal val1 As I, ByVal val2 As U) End Sub Public Overrides Sub Foo4(Of A, B, C)(ByVal val1 As A, ByVal val2 As B) End Sub End Class
[C# code] public class Person<T, U> { public virtual void Foo1<I>(T val1) {} public virtual void Foo1<I>(int val1) ...
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.