Tyepd arrays do actually implement IEnumerable<T>. I'm not sure how
to prove this with the documentation, object browser, or Reflector,
but the following code demonstrates it:
private static void Test<T>(IEnumerable<TthingToEnumerate)
{
int[] ints = null;
Test(ints); // works
Array array = null;
Test(array); // doesn't work
}
Also technically a collection does not need to implement IEnumerable
to work with foreach--it only needs a GetEnumerator() method. It's
technically possible to write a class that has GetEnumerator() and
doesn't implement IEnumerable and it will still work with
foreach--although you never want to, just a silly little technicality.
Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.
On Mon, 14 May 2007 18:50:42 +0200, "Alberto Poblacion"
<ea******************************@poblacion.orgwro te:
>
The reason why the foreach does an unsafe cast, is because it doesn't
know otherwise. A foreach can be done on any object that implements
IEnumerable, and IEnumerable returns a GetEnumerator which provides an
IEnumerator which has a method "Current" that returns Object. Therefore,
foreach always thinks that it is dealing with Object, so it always has to do
an unsafe cast regardless of the type of variable that you use to control
the loop. That is, the compiler translates the previous foreach to something
similar to the following:
IEnumerator e = vals.GetEnumerator();
while (e.MoveNext())
{
object obj = e.Current();
uint x= (uint) obj;
Console.WriteLine(x);
}
There is an IEnumerable<Tthat solves the preceding problem. However,
the documentation of System.Array only shows arrays to implement
IEnumerable, and not IEnumerable<typeoftheelements>.