FOREACH does not determine Object type?
Quote:
> Wy would to first code not work? In VB6 this works so one would expect this
> to work in C# in the same way (FOREACH came from VB I believe).
I personally think the C# way of doing it is the natural way - not
having used VB much at all. The key, of course, is to read the
specification, which says (amongst other things):
<quote>
A foreach statement of the form:
foreach (ElementType element in collection) statement
corresponds to one of two possible expansions:
* 2 If the collection expression is of a type that implements the
collection pattern (as defined above), the expansion of the foreach
statement is:
Enumerator enumerator = (collection).GetEnumerator();
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
Quote:
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
Quote:
}
[...]
* 3 Otherwise; the collection expression is of a type that
implements System.IEnumerable, and the expansion of the foreach
statement is:
IEnumerator enumerator =
((System.IEnumerable)(collection)).GetEnumerator();
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
Quote:
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
Quote:
}
</quote>
Given that, it makes perfect sense that you'd get an exception if you
try to tell foreach that each element in the collection is a Foo an one
turns out not to be.
--
Jon Skeet
If replying to the group, please do not mail me at the same time