Like classes, interfaces can be generic. Below is an example of a generic interface with a single type parameter.
1
2
3
4
5
6
| 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).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| 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:
1
2
3
4
5
6
| 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(); |