#441 – Implementing Interface Members Explicitly
October 26, 2011 3 Comments
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();
Pingback: #451 – Implement Interface Explicitly to Simplify How a Class Appears to Clients « 2,000 Things You Should Know About C#
Pingback: #456 – Explicitly Implemented Interface Members Are Automatically Private « 2,000 Things You Should Know About C#
Pingback: #799 – Interface Members Are Implicitly Public | 2,000 Things You Should Know About C#