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?
You should use the
usingstatement for what it is designed for: disposing an unmanaged resource in a timely manner. If that’s not what you’re usingusingfor, you’re probably doing something wrong.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
Disposeon it.I recommend that if you have further questions about the usage of
usingthat you read section 8.13 of the C# 4 specification.