#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