#440 – A Class Can Implement More than One Interface

It’s possible for a class to implement more than one interface.

For example, a Cow class might implement both the IMoo and the IMakeMilk interfaces.  Multiple interfaces are listed after the class declaration, separated by commas.

    public class Cow : IMoo, IMakeMilk
    {
        public void Moo() { // do mooing here }
        public double Milk() { // do milking here }
    }

You can now use an instance of the Cow class to access members of either interface.

            Cow bossie = new Cow("Bossie", 12);

            // Call both IMoo and IMakeMilk methods
            bossie.Moo();                        // IMoo.Moo
            double numGallons = bossie.Milk();   // IMakeMilk.Milk

We can also set interface variables of either interface type to refer to an instance of a Cow.

            IMoo mooStuff = bossie;
            IMakeMilk milkStuff = bossie;

            mooStuff.Moo();
            numGallons = milkStuff.Milk();
Advertisements

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.

One Response to #440 – A Class Can Implement More than One Interface

  1. Pingback: #601 – A Class Can Both Inherit and Implement an Interface « 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: