ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

TryDispose

Dispose an object if it implement IDisposable. Especially useful when working with interfaces and object factories, and IDisposable may or may not found on concrete class.

Source

public static void TryDispose(this object target)
{
  TryDispose(target, false);
}

public static void TryDispose(this object target, bool throwException)
{
  IDisposable disposable = target as IDisposable;
  if (disposable == null)
      return;

  try
  {
    disposable.Dispose();
  }
  catch (Exception)
  {
    if (throwException)
      throw;
  }
}

Example

IWhatever obj = factory.Create();  obj.TryDispose();

Author: MatteoSp

Submitted on: 1 okt 2008

Language: C#

Type: System.Object

Views: 4620