2

When I use a using clause on an object should I dispose this object before exiting the using block?

            using (var transaction = TransactionUtils.CreateTransactionScope())
            {
                try
                {
                    _entity.Save(entity);
                    transaction.Complete();
                }
                catch // or better finally
                {
                    transaction.Dispose(); // Is this try-catch usefull?
                    throw;
                }
            }

Note : A similar question has already been asked but I find the example and the answers strange.

Community
  • 1
  • 1
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • You refer to previous question in general, could you provide a link or links? What about them do you find confusing, what do they say? – Servy Dec 12 '12 at 15:11
  • This is well explained in the [msdn documentation](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) – Steve B Dec 12 '12 at 15:11

2 Answers2

3

Your transaction will be disposed automatically when exiting the using block.

This works under the hood like a try-finally block.

So there is no need to dispose the transaction manual from your code

lboshuizen
  • 2,746
  • 17
  • 20
1

It is redundant to dispose the object.

using (ResourceType resource = CreateResource())
{
    DoStuffWith(resource);
}

is equivalent to

ResourceType resource = CreateResource();

try
{
    DoStuffWith(resource);
}
finally
{    
    if (resource != null)
    {
        ((IDisposable)resource).Dispose();
    }
}

For non-nullable value types the null-check is omitted and dynamic is handled slightly different, too. See 8.13 in the C# Language Specification for more details.

Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143