I wanted to have more precise control over the lifetime of objects I was keeping in a list rather than wait for the GC. I came up with the code below which adds a few extension methods for handling IDisposable objects in a generic list. This was more elegant than adding a helper class.
I only implemented what I needed for the current project but these are very straightforward to do.
Sample code below.
using System; using System.Collections.Generic; namespace MyExtensions { public static class Extensions { /// Remove tail, starting at index. public static void RemoveTail<T>(this List<T> list, int index) { if (index >= list.Count) { return; } if (typeof(IDisposable).IsAssignableFrom(typeof(T))) { List<T> temp = list.GetRange(index, list.Count - index); ClearAndDispose(temp); } list.RemoveRange(index, list.Count - index); } public static void ClearAndDispose<T>(this List<T> list) { if (typeof(IDisposable).IsAssignableFrom(typeof(T))) { foreach (T obj in list) { IDisposable iFace = (IDisposable)obj; iFace.Dispose(); } } list.Clear(); } } //*** Extensions } //*** namespace
Usage is simple.
using MyExtensions; ... var myList = new List<HugeObject>(); ... myList.RemoveTail(idx); ... myList.ClearAndDispose();