CSharp - Explicit Interface Implementation

Introduction

Implementing multiple interfaces may result in a collision between member signatures.

You can resolve such collisions by explicitly implementing an interface member.

Consider the following example:

interface I1 { 
   void Test(); 
}
interface I2 { 
   int Test(); 
}

public class MainClass : I1, I2
{
       public void Test()
       {
         Console.WriteLine ("MainClass's implementation of I1.Test");
       }

       int I2.Test()
       {
         Console.WriteLine ("MainClass's implementation of I2.Test");
         return 42;
       }
}

Both I1 and I2 have Test method and they have the same signature.

MainClass explicitly implements I2's Test method.

This lets the two methods coexist in one class.

The only way to call an explicitly implemented member is to cast to its interface:

MainClass w = new MainClass();
w.Test();            // MainClass's implementation of I1.Test
((I1)w).Test();      // MainClass's implementation of I1.Test
((I2)w).Test();      // MainClass's implementation of I2.Test

Related Topics

Quiz