For each cycle, immediately exits

I am converting a VB6 project to C #. I came across some VB6 which I do not quite understand (and I have no way to debug at all). This is a loop that exits immediately before doing anything:

For Each objSubFolder In objFolder.SubFolders Exit For Next 

Can anyone explain this? I'm sure he is doing something. I guess it assigns a variable or something else. If so, does it do it only once?

+4
source share
3 answers

If objSubFolder exists outside the scope for each (according to your comment), the code will be roughly equivalent to this C #

 var folders = Directory.GetDirectories(@"c:\someFolder"); var firstFolder=folders.FirstOrDefault(); 

i.e. find the first subfolder of this folder (if it exists).

+6
source

This code is basically complete no-op. The only potentially significant effect this code has is that it will execute the objFolder.SubFolders property or method. If this member has a noticeable side effect, this code may be significant.

This is the rough equivalent of the following C # code

 object objSubFolder = null; using (var e = objFolder.SubFolders.GetEnumerator()) { if (e.MoveNext()) { objSubFolder = e.Current(); } } 

Please note that this is still not necessarily a 1-1 translation.

  • If objSubFolder previously defined in the method, it would incorrectly replace its value in the collection of empty folders
  • if the VB code had Option Explicit Off , then you might need to convert objFolder.SubFolders to dynamic in order to get closer to the same behavior.
+4
source

Exit For breaks out of the loop - basically the C # break keyword. It does not look like this cycle is doing something practical.

+3
source

Source: https://habr.com/ru/post/1400113/


All Articles