Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created September 27, 2016 11:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkouba/064a06f52601a689dd152d87d414a811 to your computer and use it in GitHub Desktop.
Save tkouba/064a06f52601a689dd152d87d414a811 to your computer and use it in GitHub Desktop.
Generic list with automatic dispose
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyCollections
{
/// <summary>
/// Represents a strongly typed list of disposable objects that can be accessed by index.
/// Provides methods to search, sort, and manipulate lists and disposes all contained objects.
/// </summary>
/// <typeparam name="T">The type of elements in the list, elements must implement <see cref="System.IDisposable"/>.</typeparam>
public class DisposableList<T> : List<T>, IDisposable where T : IDisposable
{
/// <summary>
/// Initializes a new instance of the DisposableList class that
/// is empty and has the default initial capacity.
/// </summary>
public DisposableList()
{ /* NOP */ }
/// <summary>
/// Initializes a new instance of the DisposableList class that
/// is empty and has the specified initial capacity.
/// </summary>
/// <param name="capacity">The number of elements that the new list can initially store.</param>
/// <exception cref="System.ArgumentOutOfRangeException">capacity is less than 0.</exception>
public DisposableList(int capacity)
: base(capacity)
{ /* NOP */ }
/// <summary>
/// Initializes a new instance of the DisposableList class that
/// contains elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <exception cref="System.ArgumentNullException">collection is null.</exception>
public DisposableList(IEnumerable<T> collection)
: base(collection)
{ /* NOP */ }
#region IDisposable Members
~DisposableList()
{
Dispose(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting
/// unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
while (Count > 0)
{
if (this[0] != null)
this[0].Dispose();
RemoveAt(0);
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment