I'm iterating over a ManageObjectCollection.( which is part of WMI interface).
However the important thing is, the following line of code. :
foreach (ManagementObject result in results) { //code here }
The point is that ManageObject also implements IDisposable, so I would like to put "result" variable in a using block. Any idea on how to do this, without getting too weird or complex?
Due to operator precedence, you cannot put braces around the inner foreach loop. This is structured very much like the nested for loop. The outer foreach is iterating over the values in bvec , passing them to the inner foreach , which iterates over the values in avec for each value of bvec .
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it. Also you should avoid to open your php tags ten thousands times for a better visibility into your code :) <?
Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.
The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.
foreach (ManagementObject result in results) using(result) { //code here }
It's not normally good practice to assign the variable outside the using
block because the resource would be disposed but could stay in scope. It would, however, result in clearer code here because you can nested the using
statement against the foreach
.
EDIT: As pointed out in another answer, ManagementObjectCollection
also implements IDisposable
so I have added that into a using
block.
No need to place ManagementObjectCollection
in a using statement. the foreach
will call Dispose()
on the enumerator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With