Is there some rare language construct I haven\'t encountered (like the few I\'ve learned recently, some on Stack Overflow) in C# to get a value representing the current iter
I disagree with comments that a for
loop is a better choice in most cases.
foreach
is a useful construct, and not replaceble by a for
loop in all circumstances.
For example, if you have a DataReader and loop through all records using a foreach
it automatically calls the Dispose method and closes the reader (which can then close the connection automatically). This is therefore safer as it prevents connection leaks even if you forget to close the reader.
(Sure it is good practise to always close readers but the compiler is not going to catch it if you don't - you can't guarantee you have closed all readers but you can make it more likely you won't leak connections by getting in the habit of using foreach.)
There may be other examples of the implicit call of the Dispose
method being useful.