I was experimenting with C# 7's new features and especially local methods. I wrote the Linq Where Operator.
I implemented the iterator block as a local method (indeed I read articles saying that local methods are a perfect solution for async methods and iterators).
I'm wondering if there is a difference between those two implementations, and if not which one is the best?
First implementation:
Here I introduced new generic type parameter for the local method, new names for the parameters...
public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
if(source == null) throw new ArgumentNullException(nameof(source));
if(predicate == null) throw new ArgumentNullException(nameof(predicate));
return WhereIterator(source, predicate);
IEnumerable<TSequence> WhereIterator<TSequence> (IEnumerable<TSequence> localSource, Func<TSequence, bool> localPredicat) {
foreach(TSequence item in localSource) {
if(localPredicat(item)) {
yield return item;
}
}
}
}
Second implementation:
No new generic parameter, no new parameters since the local method can capture the variables of the enclosing method.
public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
if(source == null) throw new ArgumentNullException(nameof(source));
if(predicate == null) throw new ArgumentNullException(nameof(predicate));
return WhereIterator();
IEnumerable<TSource> WhereIterator () {
foreach(TSource item in source) {
if(predicate(item))
yield return item;
}
}
}
}
Your second implementation is better. The main difference is that the second implementation captures its parameters implicitly, freeing you from repeating yourself:
Avoiding repetition is a very important programming practice, so you should prefer your second implementation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.