Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 703
Reuven Bass Avatar asked Apr 03 '12 15:04

Reuven Bass


2 Answers

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.

like image 68
Eric Lippert Avatar answered Sep 29 '22 19:09

Eric Lippert


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.

like image 38
Sam Axe Avatar answered Sep 29 '22 20:09

Sam Axe