I want to use using
statement purely for scope management. Can I omit holding an explicit reference to the underlying object that implements IDisposable
?
For example, giving this declaraions:
class ITransactionScope : IDisposable {}
class TransactionGuard : ITransactionScope {...}
class DbContext
{
public IDisposable ITransactionScope()
{
return new TransactionGuard();
}
}
Can I do the following:
void main()
{
var dbContext = new DbContext();
using (dbContext.TransactionScope())
{
// the guard is not accessed here
}
}
Is TransactionGuard
instance alive during using
statement?
I want to use the
using
statement purely for scope management.
You should use the using
statement for what it is designed for: disposing an unmanaged resource in a timely manner. If that's not what you're using using
for, you're probably doing something wrong.
Can I omit holding an explicit reference to the underlying object that implements
IDisposable
?
As another answer pointed out: you already typed the code in; you could have simply tried it.
Yes, you can do that. The compiler will create an invisible local variable for you and call Dispose
on it.
I recommend that if you have further questions about the usage of using
that you read section 8.13 of the C# 4 specification.
It is alive until you dispose of it. So, yes.
And this type of question is SO much easier for you to answer by just hiting the compile and run button. YOU ALREADY TYPED THE CODE. TRY 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