Follow @RoyOsherove on Twitter

Iterating over collections - As simple as possible, but no simpler.

Weekend was amazing. 'Nuff said.
Now for something completely different.
Julie asks why not allow VB.Net developers have an easier and shorter syntax to use when iterating over collections:

For Each cust as Customer in Customers

Why stop there?

Why do I even have to (re-)define what the objects in Customers are?

Why can't I just write

for each whateverthehecktheobjectsareinmycollection in Customers

and have .net look at that and say “well d'uh, I know what whateverthehecktheobjectsareinmycollection is going to be because Customers is filled with Customer objects, so I will just implicitly cast the whateverthehecktheobjectsareinmycollection to a Customer.


Well, if you did that you would lose the ability to use polymorphism, or, it would be too hard for the compiler to do for you. For example, You have a collection of objects that all implement 2 interfaces: IAnimal and ICarnivore.
Say that your collection is of strongly types with "IAnimal" but what you really want to do is loop on all ICarnivors in the collection and operate on their methods.
How do you tell the compiler to do that?
A solution would be to say "OK, you can use the old syntax or the new syntax,. With the new syntax the object defaults to whatever the collection is of (IAnimal in this case). But that leads to less readable code (Remember what happens in VB6 when you declare something without specifying a type? It's a variant. And find me a good developer that says its OK to declare a variable as variant simply by omitting the type at declaration. None. It's simply less readable.) 
The code in question is less readable because now the developer reading the code needs to look inside the loop to find out exactly what is the type of the iterator variable and how its going to be used.
So, you're back to square one. It's more readable (and developer friendly) to declare what type(or interface) you're iterating for. Better readability is simply a side effect. The real benefit is the ability to use polymorphism of many different types over the same collection.
The same claim can be said about the C# iteration syntax, where you also define the type of the iterator.

More Lookup table techniques

Weekend off