Dejas
Dejas

Reputation: 3621

What is the thinking behind having foreach cast to the variable type?

Seems like we could just have a normal statically checked assignment. I'm not sure I see the advantage in this case. What am I missing?

Upvotes: 3

Views: 131

Answers (2)

Rick Sladkey
Rick Sladkey

Reputation: 34240

The history of foreach predates generic IEnumerable and so it facilitated enumerating over collections such as ArrayList. Now that .NET has generic collections and ArrayList is rarely used, the free casting does seem like a bit of an impedance mismatch with the way it would have been designed if the feature were added now.

Nevertheless, now that we have the feature, you still see people use it even with generic collections to cast up to the type that they know they want, thereby avoiding a few lines of code. This is not too far removed from how it was used in the ArrayList days.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

The issue here is that foreach was designed prior to generics, which didn't exist until .NET 2.0. With .NET 1.1, if you used a collection class, the IEnumerator interface's Current property always returns System.Object.

By having foreach do the cast, you could write:

foreach(string item in collection)

Instead of having to explicitly write:

foreach(object temp in collection)
{
     string item = (string)temp;

Granted, with .NET 2, this is not really an issue anymore.

Upvotes: 3

Related Questions