-1

Is there a best practice for iterations inside of a "using"? which is better? and maybe a why?

"using" inside of an iteration...

foreach (var currentPerson in Persons)
{
    using (var db = new SolutionModel())
    {
        //TODO: run query
    }
}

or is it better to do an iteration inside of a "using"...

using (var db = new SolutionModel())
{
    foreach (var currentPerson in Persons)
    {        
        //TODO: run query
    }
}

FYI: coding in C#

Hakubex
  • 47
  • 6

1 Answers1

3

In the first case, a new SolutionModel will be created, run querywill be called once and then Dispose() will be called on it, for every item in Persons.

In the second case, just one SolutionModel will be created and run query will be called multiple times on that one instance before it's disposed..

So there is no "best practice" at play here. You need to decide which is the correct action based on what you want to happen as Persons is enumerated.

David Arno
  • 39,599
  • 9
  • 94
  • 129