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?