Different IEnumerator.Current and IEnumerator <T> .Current exception behavior

I got the enumerator by calling IEnumerable<T>.GetEnumerator(), then I called it MoveNext()until it returned false, and then accessed the property Current. To my surprise, there were no exceptions.

Digging through MSDN, I found that the non-original version will issue if Currentit is available after MoveNext()false returns , while the general version will not .

Can someone explain this difference?

+4
source share
2 answers

undefined, , , , undefined.

- , , . default(T).

, null new object(). ArrayList , . , , . , NullReferenceException InvalidCastException. , , . , , InvalidOperationException.

+1

, , MoveNext() false, Current a undefined. : . : Current - , " " vs " " vs " ".

, , , , API, , API . - :

    static void Main()
    {
        IEnumerator<int> typed = GetInts();
        typed.MoveNext();
        Console.WriteLine(typed.MoveNext());
        int i = typed.Current;

        IEnumerator untyped = GetInts();
        untyped.MoveNext();
        Console.WriteLine(untyped.MoveNext());
        object o = untyped.Current;
    }

    static IEnumerator<int> GetInts()
    {
        yield return 4;
        yield break;
    }
+2

All Articles