Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Each x ... Next Vs. For Each x ... Next x

Tags:

syntax

vb.net

Normally, I program .NET in C#, but currently I am updating a project written in VB.NET and have noticed a curious syntax being used in For Each loops.

Is there any difference between

For Each x in collection.Items
    ...
Next

and

For Each x in collection.Items
    ...
Next x

?

I have seen both in the code here and was curious why someone would use the second variation.

like image 848
RJ Cuthbertson Avatar asked Aug 06 '12 14:08

RJ Cuthbertson


2 Answers

This is specified like so on the MSDN Reference:

You can optionally specify element in the Next statement. This improves the readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one that appears in the corresponding For Each statement.

Original can be found here - fifth para under Remarks section:

http://msdn.microsoft.com/en-us/library/5ebk1751.aspx

like image 111
Luke Baughan Avatar answered Oct 08 '22 01:10

Luke Baughan


The second version can be clearer for the reader, particularly where there are lots of nested loops. There is no other reason for it. See MSDN for more.

like image 37
David M Avatar answered Oct 08 '22 01:10

David M