3

While learning C# basics i have learned that foreach works on those collection that have implemented IEnumerable interface. So far so good but today when I have came across DirectoryInfo I got confused.

If DirectoryInfo doesn't implement IEnumerable, then how does it come that foreach works?

DirectoryInfo[] dirListing = new DirectoryInfo(@"F:\eBook").GetDirectories();

foreach (DirectoryInfo dir in dirListing)
{
    Console.WriteLine(dir.Name);
}

Please tell me.......

Michal Klouda
  • 14,263
  • 7
  • 53
  • 77

2 Answers2

10

You are using an array.

All arrays derive from the Array abstract class that does implement IEnumerable.

From Arrays (C# Programming Guide) on MSDN:

Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

The DirectoryInfo.GetDirectories() method returns an array of DirectoryInfo objects. Since all arrays "implement" IEnumerable, you can foreach over them.

One thing to note, however, is that since DirectoryInfo.GetDirectories() does return an array, it must get the entire list immediately upon being called. While this is fine for small directories, it does not work well for large directories or cases where you use the DirectoryInfo.GetDirectories(string, SearchOption) with SearchOption.AllDirectories. If you are using .NET4+ you can, and should, use DirectoryInfo.EnumerateDirectories() or one of its overloads. These have the same results, but the list is not created until it is needed.

Matthew Brubaker
  • 3,097
  • 1
  • 21
  • 18
  • Due to necessity, I have had to create a replacement for DirectoryInfo.EnumerateFiles(...). You can find my code at http://stackoverflow.com/a/13130054/21311 – Matthew Brubaker Oct 29 '12 at 21:41