Why use wrappers around actual iterator functions in LINQ extension methods?

Looking at the Microsoft implementation of the various C # LINQ methods, I noticed that public extension methods are just wrappers that return the actual implementation as a separate iterator function.

For example (from System.Linq.Enumerable.cs):

public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    return ConcatIterator<TSource>(first, second); 
}

static IEnumerable<TSource> ConcatIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second) { 
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element; 
}

What is the reason for wrapping the iterator, instead of combining them in one and directly returning the iterator?

Like this:

public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element; 
}
+6
source share
1 answer

Wrappers (.. LINQ). , (.. foreach , - ToList, Count ..). .

, :

int[] first = { 1, 2, 3 };
int[] second = null;

var all = first.Concat(second); // note that query is not executed yet
// some other code
...
var name = Console.ReadLine();
Console.WriteLine($"Hello, {name}, we have {all.Count()} items!"); // boom! exception here

first.Concat(second).

+8

Source: https://habr.com/ru/post/1016166/


All Articles