0

Use case example for explicit interface member implementation

Generally, i do understand what interface is and that to invoke a method of a particular explicit interface member implementation, you need to instantiate that particular implementor class as that specific interface type. Take for example (in C#): interface ISampleInterface { void SampleMethod(); } class ImplementationClass : ISampleInterface { // Explicit interface member implementation: void ISampleInterface.SampleMethod() { // Method implementation. } static void Main() { // Declare an interface instance. ISampleInterface obj = new ImplementationClass(); ImplementationClass obj1 = new ImplementationClass(); // Call the member. obj.SampleMethod(); //obj1.Print(); // Error -> Cannot access explicit implementation of Print() } } What i would like to know if anyone can give me a good use case for this type of implementation or a brief example. Cheers and thanks.

14th Jan 2017, 8:58 AM
Alex Soh Chye Wat
Alex Soh Chye Wat - avatar
2 Respuestas
+ 1
check this one. I wrote some interface sample. Perhaps you will find what you need there. https://www.sololearn.com/Discuss/81657/?ref=app
15th Jan 2017, 7:37 AM
Kamil Kosyl
Kamil Kosyl - avatar
0
Thanks, after much of research i had the following conclusion: Explicit interface member implementation 1. If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. See example below. 2. If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. 3. Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method. (see below) Code in C#: interface IControl { void Paint(); } interface ISurface { void Paint(); } class ExplicitInterface : IControl, ISurface { // Both ISurface.Paint and IControl.Paint will call this method instead if not explicitly defined as below. public void Paint() { Console.WriteLine("Paint method in SampleClass"); } // Explicit member implementation void IControl.Paint() { Console.WriteLine("IControl.Paint() method in SampleClass"); } void ISurface.Paint() { Console.WriteLine("ISurface.Paint() method in SampleClass"); } public static void Main() { ExplicitInterface sample = new ExplicitInterface(); IControl IControlsample = new ExplicitInterface(); ISurface ISurfacesample = new ExplicitInterface(); // Try comment either of the Paint() method and observe sample.Paint(); IControlsample.Paint(); // uses instance declaration ISurfacesample.Paint(); Console.ReadKey();
15th Jan 2017, 10:14 AM
Alex Soh Chye Wat
Alex Soh Chye Wat - avatar