If for some bizarre reason you don’t know at run-time if an object has dispose implemented, you can use this dispose-safe function:
/// ---- IsDisposable --------------------------------
///
/// <summary>
/// returns true if an object is disposable, false if not
/// you can optionally dispose of it immediately
/// </summary>
public static Boolean IsDisposable(Object Item, Boolean DeleteIfDisposable)
{
if (Item is IDisposable)
{
if (DeleteIfDisposable)
{
IDisposable DisposableItem;
DisposableItem = (IDisposable)Item;
DisposableItem.Dispose();
}
return true;
}
else
return false;
}
solved On what objects we should use dispose method ? C# 4.0