Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to IDisposable before calling Dispose()

What is the reason of casting to IDisposable before calling Dispose() ?

public interface ITransaction : IDisposable
{}
.
.
.

//in some other class:
public void EndTransaction(ITransaction transaction)
{
     if (transaction != null)
     {
          (transaction as IDisposable).Dispose(); 
          // is the following code wrong? transaction.Dispose()

          transaction = null;
     }
}

This is one of the concrete implementation of ITransaction:

public class NHibernateTransaction : ITransaction
{

     public NHibernateTransaction(NHibernate.ITransaction transaction)
     {
          this.Transaction = transaction;
     }

     protected NHibernate.ITransaction Transaction { get; private set; }

     public void Dispose()
     {
         if ( this.Transaction != null )
         {
             (this.Transaction as IDisposable).Dispose(); // this is NHibernate  ITransaction object
              this.Transaction = null;
         }
      }

}

I have seen that code snippet many times in an open source implementation of the repository pattern and I cannot seem to understand the reason behind the cast. Directly calling transaction.Dispose() inside the if clause should work just fine. Did I miss something?

The original code can be found here: NHibernateTransaction.cs

like image 271
yanong_banikanhon Avatar asked Oct 24 '22 03:10

yanong_banikanhon


1 Answers

Since ITransaction inherits from IDisposable, it is possible that the implementer has implemented IDisposable as an explicit interface implementation, in which case the cast is required in order to access the implemented members.

In such a case, casting ensures that the call will call the IDisposable.Dispose method. The cast is done to cover all bases.

If ITransaction doesn't inherit from IDisposable, but the implementer does, a cast is needed for Dispose to be callable. Such a case may fail (throwing an exception) if the implementer does not implement IDisposable.

like image 67
Oded Avatar answered Oct 27 '22 11:10

Oded