Reputation: 149
As far as I know if you uses an interface you should implement all definitions inside the interface, in this case, browsing into Enumerator struct, I noticed this struct uses IEnumerator Interface:
public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
{
public T Current { get;}
public void Dispose();
public bool MoveNext();
}
And IEnumerator is defined as this:
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
But, I don't see any implementation of IEnumerator in Enumerator, how is that possible?
Even more, I try to define my own struct and I try to use IEnumerator as the same as Enumerator struct do:
public struct myOwnStruct : IEnumerator
{
public Current { get;}
void Reset();
public bool MoveNext();
}
And, the complier say there are no implementation for IEnumerator.
So, what is the explanation that Enumerator struct uses an interface but it never provides a implementation?
Upvotes: 1
Views: 212
Reputation: 14312
explicit interface implementation
is exactly used in such cases when you have to implement two interfaces having the same method signature (Current
) and different return types (there're other uses, like hiding also).
That's, simply put, the only way to do it (compiler doesn't let you define two methods that are technically 'the same').
The signature of a method specifically does not include the return type
Upvotes: 1
Reputation: 2323
`Enumerator` provides explicit implementation of `IEnumerator<T>`. Implicit implementation is in the format InterfaceName.Method. So Enumerator have void `object Ienumerator.Current { get{/*implementation*/} }` and etc.
If you want to implement IEnumerator
in you own struct then you have two options:
public struct myOwnStruct : IEnumerator
{
public Current { get{/* implementation*/}}
public void Reset(){}
public bool MoveNext(){return true;}
}
or
public struct myOwnStruct : IEnumerator
{
IEnumerator.Current { get{/* implementation*/}}
void IEnumerator.Reset(){}
bool IEnumerator.MoveNext(){return true;}
}
More information about explicit and implicit interface implementation you can find here: implicit-and-explicit-interface-implementations
Upvotes: 0