#537 – Implement a Generic Interface with a Generic Class

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)
        {
            // ...
        }
Advertisement

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

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 )

Connecting to %s

%d bloggers like this: