I don't agree that you shouldn't do anything if you don't need the objects in the list anymore. If the objects implement the interface System.IDisposable
then the designer of the object thought that the object holds scarce resources.
If you don't need the object anymore and just assign null to the object, then these scarce resources are not freed until the garbage collector finalizes the object. In the mean time you can't use this resource for something else.
Example:
Consider you create a bitmap from a file, and decide you don't need neither the bitmap, nor the file anymore. Code could look like follows:
using System.Drawing;
Bitmap bmp = new Bitmap(fileName);
... // do something with bmp until not needed anymore
bmp = null;
File.Delete(fileName); // EXCEPTION, filename is still accessed by bmp.
The good method would be:
bmp.Dispose();
bmp = null;
File.Delete(fileName);
The same accounts for objects in a list, or any collection. All objects in the collection that are IDisposable should be disposed. Code should be like:
private void EmptySequence (IEnumerable sequence)
{ // throws away all elements in the sequence, if needed disposes them
foreach (object o in sequence)
{
// uses modern pattern-matching
if (disposableObject is IDisposable disposable)
{
disposable.Dispose();
}
}
}
Or if you want to create an IEnumerable extension function
public static void DisposeSequence<T>(this IEnumerable<T> source)
{
foreach (IDisposable disposableObject in source.OfType(System.IDisposable))
{
disposableObject.Dispose();
};
}
All lists / dictionaries / read only lists / collections / etc can use these methods, because they all implement IEnumerable interface. You can even use it if not all items in the sequence implement System.IDisposable.