#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

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.

3 Responses to #441 – Implementing Interface Members Explicitly

  1. Pingback: #451 – Implement Interface Explicitly to Simplify How a Class Appears to Clients « 2,000 Things You Should Know About C#

  2. Pingback: #456 – Explicitly Implemented Interface Members Are Automatically Private « 2,000 Things You Should Know About C#

  3. Pingback: #799 – Interface Members Are Implicitly Public | 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: