TryDispose

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();

Description

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.

Details

Double click on the code to select all.

 

;