pepe
pepe

Reputation: 149

Why Enumerator uses IEnumerator but never implement any method of this interface in C#?

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

Answers (2)

NSGaga
NSGaga

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').

Signatures and overloading

The signature of a method specifically does not include the return type

Upvotes: 1

Radin Gospodinov
Radin Gospodinov

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

Related Questions