4.12. Generic Interfaces

As part of looking at generic classes, it also makes sense to look at how generics can also be applied to the interfaces that are implemented by generic (or non-generic) classes. In many respects, generic interfaces actually conform to the same set of rules that govern the definition and usage of their non-generic counterparts. Here's a simple generic interface just to demonstrate the fundamentals of the syntax:

[VB code]
Public Interface SimpleInterface(Of T)
    Function IsValid(ByVal val As T) As Boolean
    Function GetValue() As T
    Function GetAllValues() As List(Of T)
End Interface

Public Interface ExtendedInterface(Of T)
    Inherits SimpleInterface(Of T)
    Sub Refresh()
End Interface

Public Class TestClass(Of T)
    Implements ExtendedInterface(Of T)
    . . .
    . . .
End Class
[C# code]
public interface SimpleInterface<T> {
    bool IsValid(T val);
    T GetValue();
    List<T> GetAllValues();
}
public interface ExtendedInterface<T> : SimpleInterface<T> {
void Refresh();
}
public class TestClass<T> : ExtendedInterface<T> {
    . . .
    . . .
}

If you're already familiar with working with interfaces, this should be fairly trivial. You can see here that the interface accepts a type parameter that is then littered, in different forms, through the methods supplied by the interface. This also includes an example of generic interface inheritance so you can see type parameters used in that context. Finally, to make this complete, the example adds a class that implements that interface. There should ...

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.