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.
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
}
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.
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