#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)

            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.Remember(new Joke("What's red and invisible?", "No tomatoes"));

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: