Casting and the foreach Statement
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!
Comments
# Mitsu
9/10/2006 6:14 AM
Interesting.
C# 3.0 will permit:
foreach (string s in anyCollection.Cast<String>())...
You can even filter the elements according to their type:
foreach (string s in anyCollection.OfType<String>())...
These extensions do not create any extra collection.
Like you, I like and use foreach a lot. But using C# 3, the Linq syntax is much better and may replace many foreach statements...
Regards
# mabster
9/10/2006 6:46 AM
I love the idea of "OfType<String>"! That will make the 'automatic casting' of foreach a lot less error prone!
Thanks for the feedback Mitsu!
# Mitsu
11/10/2006 4:28 AM
You are welcome and thank you for your post about my blog !