Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use "using" on a new empty DataTable?

I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();

Changing this to use using, I have:

using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}

Is that good practice (i.e. creating the empty DataTable with a using statement)? I don't know why but it doesn't feel quite right.

like image 899
EvilDr Avatar asked Dec 18 '22 17:12

EvilDr


2 Answers

As I stated in the comments, your last example won't work. If you want to do something like that, you could move the DataTable generation into a separate function:

public DataTable GetBLLDataTable()
{
    switch(foo)
    {
        case bar:
            return BLL.GetDataTable(bar);
            break;
        default:
            return BLL.GetDataTable();
            break;
    }
}

And then use the DataTable returned by this method in your using statement:

using (DataTable dt = GetBLLDataTable()) {
    // iteration logic here
}
like image 181
DiplomacyNotWar Avatar answered Dec 24 '22 00:12

DiplomacyNotWar


In your last example, you are only disposing the first DataTable object and not the other that gets assigned.

The using statement is just syntactic sugar for try/finally. You can instead write your last example like:

DataTable dt;
try
{
    switch (foo)
    {
        case bar:
            dt = BLL.GetDataTable(bar);
            break;
        default:
            dt = BLL.GetDataTable();
            break;
    }
}
finally
{
    dt?.Dispose();
}

This will ensure your IDisposable object is always disposed. It is a bit of a weird example in this case though since I don't see why you'd assign a DataTable in the switch and then immediately dispose it.

like image 40
Owen Pauling Avatar answered Dec 24 '22 02:12

Owen Pauling