Old: RAII Obliterator Pattern
I implemnted an obliterator for C#. It works around this problem:
foreach (var item in list) if (item == "two") list.Remove(item);
System.InvalidOperationException: Collection was modified;enumeration operation may not execute.
The new version of the code is one line longer:
using (var obliterator = Obliterator.From(list))
foreach (var item in list)
if (item == "two")
obliterator.Remove(item);
The Obliterator class :
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
using System;
using System.Collections.Generic;
namespace Obliterator
{
public class Obliterator<T> : IDisposable
{
ICollection<T> collection;
List<T> toRemove;
public Obliterator(ICollection<T> collection)
{
this.collection = collection;
toRemove = new List<T>();
}
public void Remove (T item)
{
toRemove.Add(item);
}
public void Dispose()
{
foreach (var item in toRemove) collection.Remove(item);
}
}
public static class Obliterator
{
public static Obliterator<T> From <T> (ICollection<T> collection)
{
return new Obliterator<T> (collection);
}
}
}