O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required