Like most C# programmers, I use the foreach statement a lot. It's a very handy little construct for iterating through collections - especially ones that don't surface an 'indexer' so you can't use a for loop.

Anyway, after doing something like this a few times:


// object[] array = ... foreach (String str in array) { Console.WriteLine(str); }


... I started to wornder why I didn't need to cast each element of the collection to String. I mean, this is an array of object, not an array of String! What's the deal with that?

As a test, I tried adding an int to my array of object, and sure enough the code crashed at runtime with an InvalidCastException. So C# appears to be doing the cast for me. Bizarre!

I ended up doing a quick search on Google to see if someone could explain this behaviour, and lo and behold, someone has!

Anyway, it's a good thing to know, and works in all sorts of situations. For example, you might have a collection of type List<Person> but you know that it's full of Employee objects. You can, therefore, do something like this:


foreach (Employee e in personList) { // ... }


Pretty handy!