What's the best practice for dealing with objects in for or foreach loops? Should we create one object outside the loops and recreate it all over again (using new... ) or create new one for every loop iteration?
Example:
foreach(var a in collection) { SomeClass sc = new SomeClass(); sc.id = a; sc.Insert(); }
or
SomeClass sc = null; foreach(var a in collection) { sc = new SomeClass(); sc.id = a; sc.Insert(); }
Which is better?
You CAN use a loop. The trick is that you have to save the reference to each one as you create it. A simple way would be to use an array. You have to declare the array outside the loop, then use your loop counter as the index into the array...
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.
For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
The first way is better as it more clearly conveys the intended scope of the variable and prevents errors from accidentally using an object outside of the intended scope.
One reason for wanting to use the second form is if you want to break out of the loop and still have a reference to the object you last reached in the loop.
A bad reason for choosing the second form is performance. It might seem at first glance that the second method uses fewer resources or that you are only creating one object and reusing it. This isn't the case here. The repeated declaration of a variable inside a loop doesn't consume any extra resources or clock cycles so you don't gain any performance benefit from pulling the declaration outside the loop.
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