Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# using statement with double IDisposable

I have following statement using using:

using (var reader = data.CreateCommand(sql).ExecuteDataReader())

in this case data is some object which internally holds SqlConnection. CreateCommand(sql) function returns SqlCommand and ExecuteDataReader returns SqlDataReader. Since SqlCommand and SqlDataReader are both IDisposable, will they both be disposed by this use of using statement?

For now I have done it like this:

using (var cmd = data.CreateCommand(sql))
using (var reader = cmd.ExecuteDataReader())

But I would like to know if it's possible to combine them as stated above?

like image 825
Jure Avatar asked Nov 15 '25 10:11

Jure


2 Answers

"if it's possible to combine them" - two using are totally fine, because both needs to be disposed.

You can combine them by extracting into method:

void RunWithReader(string sql, Action<SQLDataReader> action)
{
    using (var cmd = data.CreateCommand(sql))
    using (var reader = cmd.ExecuteDataReader())
        action(reader);
}

Then you can use lambda

RunWithReader("whatever command", reader =>
{
    ... // while(reader.Read() { ... } - this could also be extracted
});
like image 187
Sinatr Avatar answered Nov 18 '25 00:11

Sinatr


Agree with Matthew Watson's comment. You need to have both of usings statemets. Here is the related question with additional reasoning. SqlConnection SqlCommand SqlDataReader IDisposable

like image 28
klashar Avatar answered Nov 18 '25 00:11

klashar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!