How do you get the index of the current iteration of a foreach loop?

后端 未结 30 2048
刺人心
刺人心 2020-11-22 07:05

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

30条回答
  •  温柔的废话
    2020-11-22 07:42

    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.

提交回复
热议问题