0

I want to know which is the best way to use the 'using' block in C#.

Approach 1: Looping inside the 'using' block

void MyMethod(List<Prod> productList)
{
    using(MyResource mr = new MyResource())
    {
        foreach(Prod product in productList)
        {
            //Do something with the resource
        }
    }
}

Approach 2: Looping outside the 'using' block

void MyMethod(List<Prod> productList)
{
    foreach(Prod product in productList)
    {
        using(MyResource mr = new MyResource())
        {
        //Do something with the resource
        }
    }
}

I want to know which approach is preferable and why. Will there be performance differences between the two? Also how does it differ if the resource is... say a database connection or an object?

Thanks!

  • 1
    It depends on what you do inside the loop with the mr instance and if the mr instance is reusable between loops. – Steve Feb 27 '15 at 07:23
  • 4
    Both are very different things. How can you compare both? Makes no sense really. If you want new resource for each item use second, otherwise first. – Sriram Sakthivel Feb 27 '15 at 07:23
  • If your resource is "reusable", which means, iterations doesn't put the resource in the state that you can't use it anymore without reopening it, of course first approach is better, because you don't waste time and memory by creating a new object every iteration – JustSomeGuy Feb 27 '15 at 07:23
  • Very much generic question. Put exact scenario so people can help. – Amit Feb 27 '15 at 07:34
  • @EgorShkorov it's not an "of course" because how do you know that compilers don't optimise it anyway? – barlop May 14 '20 at 22:03

3 Answers3

3

In approach 1, you create your resource once for your loop.

In approach 2, you create a new resource on each Product in your product list.

Unless it is necessary the approach 2 is not recommended.

Approach 1 have a better performance, there are fever object created/destroyed (and memory consumed). Especially if it's a database, event if there are a pool connection.

Yanos
  • 1,519
  • 2
  • 12
  • 13
0

This:

using(MyResource mr = new MyResource())
{
  //Do something with the resource
}

roughly translates to this:

MyResource mr = new MyResource();
try {
  //Do something with the resource
} finally {
  mr.Dispose();
}

except that mr is not available after the closing curly bracket in the first example.

If you make this substitution in both your examples you will see how different they are. They accomplish different things - both are valid in certain circumstances.

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
-1

It decides the scope of that resource. outside that using resource(variable) will be disposed.

so it depends on your usage. generally "using" is used to create and dispose the connections, to ensure it is properly closed after desired operations.

Chaitanya Gadkari
  • 2,669
  • 4
  • 30
  • 54