Search code examples
c#using

Using statement best practice


It may be a silly question, but since I can't give it an answer by my own, I will ask it here.

Let we have a module that we want to use in an http handler (the web app is written in C# using ASP.NET) and let that this module implements the IDisposable interface. Then a common approach is to use the module as below:

using(var module = new ModuleName(param1, param2, param3))
{

}

Is it better to place any code to variables that we are going to use only inside the body of this using statement or before this. In terms of code:

Is it better (and why) the first approach or the second approach:

first approach

using(var module = new ModuleName(param1, param2, param3))
{
    int a = Request.GetParam<int>("aNumber");
    string b = Request.GetParam<string>("bString");
    // and other parameters contained to the http request
}

second approach

int a = Request.GetParam<int>("aNumber");
string b = Request.GetParam<string>("bString");
// and other parameters contained to the http request

using(var module = new ModuleName(param1, param2, param3))
{

}

If there isn't any technical reason -and it is an opinion based decision- that we should prefer the first approach to second approach or vice versa, please let me know, in order to delete my post.


Solution

  • It depends on if you need those variables outside of the scope of the using-statement. If so, you need to declare them outside anyway. If not, declare them in the using.

    Why? It's all about readability, fail-safety and refactoring.

    This is true not only for the using but scopes and variable declaration in general. Read: