#441 – Implementing Interface Members Explicitly

When you implement interface members in a class, the members are normally accessible via either a reference to the class or a reference to the interface.

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

bossie.Moo();

IMoo mooer = bossie;
mooer.Moo();

If you want interface members to be accessible only via the interface, you can implement an interface member explicitly, by prefixing the member name with the name of the interface.

    public class Cow : IMoo
    {
        void IMoo.Moo()
        {
            Console.WriteLine("Moo");
        }
    }

You can now only call this member using an interface variable.

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

            // Compile error: Cow does not contain a definition for 'Moo'
            bossie.Moo();

            // But we CAN access via IMoo
            IMoo mooStuff = bossie;
            mooStuff.Moo();
Advertisements