Time to wave goodbye to the C# “for” statement?

Lately I’ve got a bit tired of the kinda old fashioned syntax of the for-statement, especially the triple declaration of the variable to count on. As the Enumerable.Range is nice and Linq’y I’ve taken to using that, and as far as I’ve (unscientifically) measured, there’s only a small perf-hit if you approach more than about 100000 iterations.

First the old fashioned way:

for (var i = 0; i < 10; i++) Console.WriteLine(i);

Then the Enumerable way:

foreach (var i in Enumerable.Range(0, 10)) Console.WriteLine(i);

And finally, with an extension method thrown in:

public static IEnumerable<int> Range(this int i, int count)
{
    return Enumerable.Range(i, count);
}

foreach (var i in 0.Range(10)) Console.WriteLine(i);

Not big science, but in my opinion nice and clean and – most importantly – a succinct expression of programmer intent

Advertisements
Posted in C#

2 thoughts on “Time to wave goodbye to the C# “for” statement?

  1. Anonymous Guy

    Before proclaiming the death of the for loop, you might want to try removing the n-th item from a collection with either Linq or foreach. 😉

    • phejndorf

      Absolutely – there is no silver bullet. However, I find that there are few cases where element removal is conditioned by position rather than logic. In other words I recommend using the RemoveAll() method (on IList’s). As I’ve blogged here, RemoveAll() is not very hard to add as an extension method to other kinds of IENumerable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s