C# conversion question

Question:

There is a class that implements the IEnumerable interface

class MyClass : IEnumerable<int>
{
    public IEnumerator<int> GetEnumerator()
    {
        for(int i = 0; i < 100; i++)
        {
            yield return i;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)this).GetEnumerator(); //всё хорошо
        return (IEnumerable)this.GetEnumerator(); //error;
    }

Why does the compiler accept the first option, and the second one emphasizes that such a notation is not allowed, if, in theory, both of these notations are conversion operations?

Answer:

Because it thinks you want to convert an IEnumerator IEnumerable That is, it regards this as an attempt to call this.GetEnumerator() , convert the result to IEnumerable (by explicit casting) and return as IEnumerator (by implicit casting) – the return type declared in the method declaration. Just:

return this.GetEnumerator();
Scroll to Top