Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: IEnumerator<T> in a using statement

I was curious to see how the SingleOrFallback method was implemented in MoreLinq and discovered something I hadn't seen before:

    public static T SingleOrFallback<T>(this IEnumerable<T> source, Func<T> fallback)
    {
        source.ThrowIfNull("source");
        fallback.ThrowIfNull("fallback");
        using (IEnumerator<T> iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())
            {
                return fallback();
            }
            T first = iterator.Current;
            if (iterator.MoveNext())
            {
                throw new InvalidOperationException();
            }
            return first;
        }
    }

Why is the IEnumerator<T> in a using statement? Is this something that should be thought about when using the foreach on an IEnumerable<T> also?

Side question: What does this method do exactly? Does it return the fallback item whenever the source sequence does not contain exactly one item?

like image 882
Svish Avatar asked Jun 02 '09 10:06

Svish


1 Answers

IEnumerator<T> extends IDisposable, so you should have it in a using statement. foreach does this automatically. (The non-generic IEnumerator doesn't extend IDisposable but the C# compiler still generates code to call Dispose conditionally. This was one of the (few) changes between C# 1.0 and 1.2, where 1.2 is the version shipping with .NET 1.1, for some reason.)

Here's an article explaining why this is important in the context of iterator blocks.

As for what the method does:

  • If the sequence is empty, return the fallback item
  • If the sequence has exactly one item, return it
  • If the sequence has more than one item, throw an exception

PS: Nice to see MoreLinq is getting some attention :)

like image 156
Jon Skeet Avatar answered Sep 29 '22 23:09

Jon Skeet