#536 – Using a Generic Interface

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();

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #536 – Using a Generic Interface

  1. Thank you SO MUCH for that help. I was searching for this for hours.

  2. Thank you SO MUCH! That saved my day.

  3. Pingback: #1,066 – Constraining a Type Parameter on a Generic Interface | 2,000 Things You Should Know About C#

  4. Pingback: #1,067 – Covariance and Generic Interfaces | 2,000 Things You Should Know About C#

  5. Pingback: #1,069 – Contravariance and Generic Interfaces | 2,000 Things You Should Know About C#

Leave a comment