#442 – Explicit Interface Implementation Allows Duplicate Member Names

Let’s assume that a class implements more than one interface and there is a particular member that exists in both interfaces.  For example, let’s say that the Cow class implements both the IMoo and IMakeMilk interfaces and they each contain a property named Motto whose type is string.

To provide implementations for both IMoo.Motto and IMakeMilk.Motto, the Cow class must implement the interfaces explicitly, to distinguish between the two properties.

    public class Cow : IMoo, IMakeMilk
    {
        string IMoo.Motto
        {
            get { return "I moo because I want attention"; }
        }

        string IMakeMilk.Motto
        {
            get { return "Everyone should drink a little milk every day"; }
        }

        // Other Cow stuff
    }

We now must access these properties through their corresponding interfaces.

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

            // NOTE: bossie.Motto does not exist

            IMoo mooing = bossie;
            Console.WriteLine(mooing.Motto);

            IMakeMilk milking = bossie;
            Console.WriteLine(milking.Motto);

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.

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: