IEnumerable
: The Missing ForEach
Extension MethodUnlike many other languages, the .NET Framework surprisingly omits a ForEach
extension method for IEnumerable
. This absence often sparks questions, with performance worries frequently cited as a potential reason.
C#'s built-in foreach
statement already handles most iteration needs effectively. Adding a ForEach
extension method would be redundant.
Moreover, the foreach
statement's readability generally surpasses that of a ForEach()
method call:
<code class="language-csharp">// Using ForEach() extension method list.ForEach(item => item.DoSomething()); // Using foreach statement foreach (var item in list) { item.DoSomething(); }</code>
While foreach
requires more keystrokes, its clarity often wins out.
Recent conversations have highlighted potential benefits of a ForEach()
extension method:
ForEach()
provides compile-time type checking, unlike the runtime checks of foreach
.ForEach()
, exemplified by objects.ForEach(DoSomething)
.ForEach()
enables method chaining.These advantages suggest that a standardized ForEach()
method could be a valuable addition to future .NET versions.
The above is the detailed content of Why Doesn't .NET's `IEnumerable` Have a `ForEach` Extension Method?. For more information, please follow other related articles on the PHP Chinese website!