Why does it matter which interface's method is called? Both methods are identical with the same name.
And maybe that's okay. But maybe it's not.
In this case the result of the method is to output "I1 Interface Method", indicating that in real code the equivalent does care that it's I1
.
When we create methods we give them names that try to be short and clear in meaning based on the meaning a word or few words have in a natural language like English. This can result in there in fact being different (whether very different or subtly so) purposes to two methods with the same name. We would then want to have separate implementations.
It's nice when things line up so that we can indeed use the same method for both, but it's also great that we're not trapped by that when inappropriate.
We'd also have to have separate implementations for interfaces with methods with the same name and parameter signature but different return types, since C# can't distinguish between these. A common example is IEnumerable<T>
since it has a GetEnumerator()
method that returns IEnumerator<T>
but inherits from IEnumerable
which has a GetEnumerator()
method that returns IEnumerator
. (IEnumerator<T>
and IEnumerator
are also examples of this same principle).
Another case where we might want to do explicit interface implementation is when a member isn't very useful in the context of the concrete type. For example List<T>
implements ICollection<T>
. That interface has an IsReadOnly
property that is pointless in the context of working with List<T>
directly as we know it's false because List<T>
s are inherently not read-only. It is important when we're working on an ICollection<T>
reference though (and of course, the rules require it be implemented one way or another), so it's done as an explicit implementation. ReadOnlyCollection<T>
not only does the same thing (but of course, returning true
instead of false
) but also makes methods like Add()
which are clearly pointless given that they will always throw an exception no matter what, explicit.