What are we coming to?

16. June 2010 Rant 0

For the past 4 years, .Net has been my framework of choice.  Prior to that, I used Visual C++ for 6 years.  There are some great things about .NET that I didn’t have with C++.  But with these great techniques comes a high responsibility, and that is, to understand what it is that the framework is doing for you. Most people who have used .NET for a week or more know about the foreach command.  It’s great, it lets us iterate through lists and always have a type-safe object to deal with.  We don’t have to worry about the number of items in a list, and whether the list is 0 or 1 indexed (0, by the way). However, this causes some problems as well.  Recently I was on a forum and someone asked if there is a way to go through a list in reverse order.  This guy had a list of objects, for example People.  If these are sorted from A-Z on last name, he wanted to work backwards and go from Z-A but there isn’t a foreachreverse command.

He has two options:

1.  He could use the Reverse() extension method in Linq, and have something like

foreach(var obj in Persons.Reverse()) { }

2.  He could break down and write a good old fashioned loop

for(int i = Persons.Count -1; i >= 0; --i)
{       
    Person p = Persons[i]; 
}

Truth be told, option #1 is probably optimized in the CLR, but every developer should instantly think of option #2 before looking to see if there are better ways of doing things, which sadly was not the case here.


Leave a Reply

Your email address will not be published. Required fields are marked *