TryDispose - Yortw/Yort.Trashy GitHub Wiki
TryDispose is an extension method that targets both System.Object and System.IDisposable. System.Object is targeted to allow use with types that explicitly implement IDisposable, or for references that use types that have no direct relation IDisposable even if the instance referenced implements it. The purpose of TryDispose is to eliminate repetitive code often associated with disposing object instances, including;
- Checking the reference is not null
- Checking if the reference actually implements IDisposable
- Optionally suppressing exceptions from Dispose()
- Disposing one or more instances held in an IEnumerable
- Disposing an IEnumerable type itself, if it also implements IDisposable
To use this extension, ensure the following using statement appears at the top of your source file
using Yort.Trashy.Extensions;
Examples
Dispose an object if it implements IDisposable and ignoring if it is a null reference.
// Disposes 'disposable' if it implements IDisposable and is not null
// otherwise, does nothing
disposable.TryDispose();
Dispose an object if it implements IDisposable, ignoring if it is a null reference and suppress any exceptions thrown during disposal.
// Disposes 'disposable' if it implements IDisposable and is not null
// otherwise, does nothing. If an exception is thrown from the Dispose
// method it is suppressed/ignored.
disposable.TryDispose(DisposeOptions.SuppressExceptions);
Dispose all objects in a collection, if they are not null and implement IDisposable, suppressing exceptions, and also dispose the collection itself if it too supports IDisposable. The items will be disposed first, then the collection. Any item that is null or does not implement IDisposable will be ignored. You can all the overload without options, or pass DisposeOptions.None if you do not want to pass exceptions.
// Assuming 'items' is an enumerable, disposes each item inside 'items'
// if it implements IDisposable and is not null otherwise, and then disposes
// 'items' itself if it implement IDisposable.
// Supresses/ignores any exceptions during any call to Dispose.
items.TryDispose(DisposeOptions.SuppressExceptions);