C# - Explicit interface implementation

  • Note:
    • To handle case where two interfaces have the same method names.
    • Explicit implementation of an interface cannot have access modifiers.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
interface I1
{
void InterfaceMethod();
}

interface I2
{
void InterfaceMethod();
}

public class Program: I1, I2
{
void I1.InterfaceMethod()
{
//...
}
void I2.InterfaceMethod()
{
//...
}
public static void Main()
{
Program p = new Program();
// Explicitly cast
((I1) p).InterfaceMethod();
((I2) p).InterfaceMethod();
}
}
  • Explaination:
    • To ensure that when a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.