1

I believe, I know the answer. But, trying to get a confirmation. If, you do something like:

foreach (string str in Directory.GetFileSystemEntries(path)) { Console.WriteLine(str); }

Instead, of:

string[] directoryEntries = Directory.GetFileSystemEntries(path);
foreach (string str in directoryEntries) { Console.WriteLine(str); }

Directory.GetFileSystemEntries(path), behind the scenes, will only get executed once, correct? I assume it makes, in this case, the necessary string[] and then does it's looping. Has too ...

tobeypeters
  • 464
  • 3
  • 11

1 Answers1

4

Yes it will only get executed once. You are correct. How to check it? Here is a snippet you could have write to see it.

public static void Main()
{
    var ints = new int[]{0,2,5,8};
    foreach (var i in Print(ints))
    {
        Console.WriteLine(i);
    }
}

public static int[] Print(int[] numbers)
{
    Console.WriteLine("Hello");
    return numbers;
}

Output is:

Hello
0
2
5
8

Try this demo online

Hello is printed only once!

A better way would have been to use a debbuger and follow the flow step by step. A more advance way would have been to read the MSIL :)

aloisdg
  • 22,270
  • 6
  • 85
  • 105