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?
IEnumerator<T>extendsIDisposable, so you should have it in a using statement.foreachdoes this automatically. (The non-genericIEnumeratordoesn’t extendIDisposablebut the C# compiler still generates code to callDisposeconditionally. 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:
PS: Nice to see MoreLinq is getting some attention 🙂