Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining foreach and using

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?

like image 937
apoorv020 Avatar asked Jun 09 '10 11:06

apoorv020


People also ask

Can we use foreach inside foreach?

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 .

Can we use for loop inside foreach loop?

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 :) <?

Does foreach call Dispose?

Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.

What is the use of foreach loop?

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.


1 Answers

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.

like image 197
David Neale Avatar answered Oct 04 '22 12:10

David Neale