Explicit Interface Implementation in C# with Example

Explicit Interface Implementation in C# with Example
Rating: 5 - 1 Votes

Explicit Interface Implementation in C# with Example

Explicit Interface Implementation in C# with Example

Explicit Interface Implementation in C# with Example

We know how interface works in C#.  But in some cases, we encounter a situation where 2 interfaces have a method of same name and signature.  Since your class or structure can inherit from multiple interfaces, there will be ambiguity about which method you want to call.  To resolve this issue, we make use of explicit interface implementation, so that we can make it clear which method belongs to which interface.  For explicit interface implementation, we use interface name in front of the method name while implementing it and also we are not allowed to use any access modifier in front of it.

To call your desired method, you simple need to typecast the reference variable using an interface name to which that specific method belongs.  You can also make one of the methods as default implementation by implementing it implicitly, but its good practice to go for explicit implementation, so that things should be much clear.

 Output:

Call to Interface 1
Call to Interface 2
Press any key to continue . . .

From inheritance in C#, we know that a base class reference variable can point to the derived class object.  You can use same logic in case of interface to call your desired method without typecasting it.

Output:

Call to Interface 1
Call to Interface 2
Press any key to continue . . .