…or “Short rant on why C-style for-loops are almost always unnecessary “…
If you’ve been with C# for the last couple of years, your coding style has probably evolved in a more functional direction since the introduction of C# 3/.NET 3.5 with all its LINQ and lambda goodness.
In my own code, I have almost completely dismissed the old C-style for-loop in favor of .Select, .Where etc., making the code way more readable and maintainable.
The readability and maintainability is improved because long sequences for for/ foreach and collection-juggling can now be replaced by oneliners of selection, mapping, and projection.
One place, however, where I often see the for-loop used, is when people need to build sequences of repeated objects, or where some variable is incremented for each iteration.
Now, here is a message to those developers: Please realize that what you actually want to do is to repeat an object or map a sequence of numbers to a sequence of objects.
Having realized that, please just implement it like that:
1 2 |
// repeat some object var repeatedStrings = Enumerable.Repeat("HELLO", 5000); |
Same thing goes for sequences of elements where something is incremented:
1 2 3 |
// map sequence of numbers to objects var sequenceOfHourObjects = Enumerable.Range(0, 24) .Select(hour => new SomeHourObject { Hour = TimeSpan.FromHours(hour) }); |
There’s just too many for-loops in the world!
Not the same thing, but still somehow related to that, is when people need to collect stuff from multiple properties and ultimately subject each value to the same treatment – please just implement it like that:
1 2 3 |
// collect stuff and capitalize var capitalizedStrings = new [] { obj.FirstName, obj.AnotherName, obj.ThirdName } .Select(s => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s)); |
</rant>