#537 – Implement a Generic Interface with a Generic Class
March 12, 2012 Leave a comment
When a class makes use of a generic interface, it can choose to implement the constructed interface, supplying all type parameters for the interface.
public class Farmer : IRememberMostRecent<Joke>
A class can also implement a generic interface, as long as the class itself is generic. Type parameters for the interface are supplied to the class when it is constructed.
public class Dog<T> : ICanEat<T>
This type parameter (or parameters) can then be used in instance methods that implement the interface.
// ICanEat.Eat public void Eat(T thingToEat) { // ... }
You can also use the type parameter passed to the class in instance methods that are not part of the interface.
// Not part of the interface public void PlayWith(T thingToPlayWith) { // ... }