#536 – Using a Generic Interface
March 9, 2012 5 Comments
Like classes, interfaces can be generic. Below is an example of a generic interface with a single type parameter.
public interface IRememberMostRecent<T> { void Remember(T thingToRemember); T TellMeMostRecent(); List<T> PastThings { get; } }
When a class implements this interface, it can choose to fully construct the interface (provide a type).
public class Farmer : IRememberMostRecent<Joke> { public string Name { get; protected set; } public Farmer(string name) { Name = name; lastJoke = null; allJokes = new List<Joke>(); } // IRememberMostRecent implementation private Joke lastJoke; private List<Joke> allJokes; public void Remember(Joke jokeToRemember) { if (lastJoke != null) allJokes.Add(lastJoke); lastJoke = jokeToRemember; } public Joke TellMeMostRecent() { return lastJoke; } public List<Joke> PastThings { get { return allJokes; } } }
Using the Farmer class:
Farmer burton = new Farmer("Burton"); burton.Remember(new Joke("A man walks into a bar.", "Ouch")); burton.TellMeMostRecent().Output(); burton.Remember(new Joke("What's red and invisible?", "No tomatoes")); burton.TellMeMostRecent().Output();