Can I use the using statement with RHV (right value)?

I want to use the using statement to control the scope. Can I omit the explicit reference to the underlying object that implements IDisposable ?

For example, using these ads:

 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 active during using statement?

+6
source share
2 answers

I want to use the using statement only for scope management.

You must use the using statement for what it is intended to: Dispose of an unmanaged resource in a timely manner. If this is not what you are using for, you are probably doing something wrong.

Is it possible to omit the explicit reference to the base object that implements IDisposable ?

As another answer indicated: you have already typed the code; you could just try it.

Yes you can do it. The compiler will create an invisible local variable for you and call Dispose on it.

I recommend that you have additional questions about using using that you read in section 8.13 of the C # 4 specification.

+10
source

He is alive until you get rid of him. So yes.

And this type of question is much easier for you by simply pressing the compile and run button. YOU ARE ALREADY TYPES OF CODE. TRY IT.

+2
source

Source: https://habr.com/ru/post/912324/


All Articles