Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Fail For Enumerator

Tags:

c#

I want to implement a IEnumerator. But It causes a error

public class WachableDictionaryEnumerator : IEnumerator<TVal>
{
    private TVal[] a;
    private int len;
    public bool MoveNext()
    {
        len = len + 1;
        return len < a.Length;
    }
    public object Current
    {
        get
        {
            return a[len];
        }
    }
    public TVal Current
    {
        get
        {
            return a[len];
        }
    }
    public void Dispose()
    {
        a = null;
        len = 0;
    }
    public void Reset()
    {
        len = 0;
    }
}

The error is:

Error 5 The type 'CPS.Manipulation.WatchableDictionary.WachableDictionaryEnumerator' already contains a definition for 'Current' D:\CE\Supins\Cyan Pembuat Soal\Required Manipulation\Class1.cs 32 25 Required Manipulation

But if I delete one of Current object, then the error is

Error 21 'CPS.Manipulation.WatchableDictionary.WachableDictionaryEnumerator' does not implement interface member 'System.Collections.Generic.IEnumerator.Current'. 'CPS.Manipulation.WatchableDictionary.WachableDictionaryEnumerator.Current' cannot implement 'System.Collections.Generic.IEnumerator.Current' because it does not have the matching return type of 'TVal'. D:\CE\Supins\Cyan Pembuat Soal\Required Manipulation\Class1.cs 16 22 Required Manipulation

Help me to fix the code.

like image 601
Christian Irwan Hadi Wicaksana Avatar asked Feb 21 '26 21:02

Christian Irwan Hadi Wicaksana


1 Answers

You need to use explicit interface implementation for one of either IEnumerator.Current or IEnumerator<T>.Current. Typically you implement the non-generic interface explicitly (where you need to), and make that implementation delegate to the generic one:

// Explicit interface implementation
object IEnumerator.Current { get { return Current; } }

// Normal implementation
public TVal Current { get { return a[len]; } }

Note that in order to get the first element correctly, you should initialize len to -1 to start with (and on Reset)... and ideally validate len in the Current property.

Note that when implementing IEnumerable<T> you need to do the same thing, e.g.

public IEnumerator<string> GetEnumerator()
{
    // Whatever
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}
like image 179
Jon Skeet Avatar answered Feb 24 '26 11:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!