Exploring MoreLINQ Part 21 - Side Effects
The next video in my exploring MoreLINQ series looks at a few methods that relate to "side-effects" - Trace
, Pipe
, ForEach
and Consume
.
In my talk at Techorama NL next week, one of the things I will be strongly recommending is avoiding side-effects wherever possible in LINQ. But as with all rules, there are exceptions, and so these methods can be very helpful if used appropriately.
ForEach
provides the same capability that is on List<T>
to any IEnumerable<T>
allowing you to call an action on every element in a sequence. Personally, I don't mind using a foreach
construct for this purpose, but at least this method avoids an unneccessary ToList
which I see a lot from developers who like putting a ForEach
on the end of a chain.
Pipe
allows you to perform an action on an element as its pulled through the pipeline. The best use for this is probably diagnostics - you may want to log intermediate values for debugging purposes. And Trace
is a simplified version that just writes the element to trace.
Finally, Consume
pulls all elements through the sequence but discards them. The only reason you'd need this is if there was some side-effect that you wanted to make happen, but you didn't care for the final result. Personally, I think this one is probably a code smell if you see it in the wild. There's usually a better way to achieve the same result.
You can find all videos in this series here.