Skip to main content

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


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