Nerd wannabe

lazy weblog

Old: RAII Obliterator Pattern

leave a comment »

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);
   }
 }
}

Advertisements

Written by vlad

August 22, 2009 at 2:13 pm

Posted in laugh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: