This is called an "explicit interface implementation". The reason for this may be, for example, a name conflict.
Consider the IEnumerable
and IEnumerable<T>
interfaces. One declares a non-generic method
IEnumerator GetEnumerator();
and the other is general:
IEnumerator<T> GetEnumerator();
In C #, it is not allowed to have two methods with the same name that differ only in return type. Therefore, if you implement both interfaces, you need to declare one method explicit:
public class MyEnumerable<T> : IEnumerable, IEnumerable<T> { public IEnumerator<T> GetEnumerator() { ...
Explicitly implemented interface methods cannot be called on instance variables:
MyEnumerable<int> test = new MyEnumerable<int>(); var enumerator = test.GetEnumerator();
If you want to call a non-generic method, you need to drop test
to IEnumerable
:
((IEnumerable)test).GetEnumerator();
This also, apparently, is the reason that access modifiers (for example, public
or private
) are not allowed in explicit implementations: in any case, it is not displayed in the type.
source share