I can now rewrite my function that needs to eliminate expired items to call my algorithm like so:
RemoveItems<Item>.Execute(collection, delegate(Item item) { return item.expired == true; });
Note that I am using the new anonymous method feature of C# to allow me to express the decide method inline in my caller code.
The complete example program looks like this:
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
#endregion
namespace UpdateIteration
{
public static class RemoveItems<T>
public delegate bool Decide(T item);
public static void Execute(ICollection<T> collection, Decide decide)
List<T> removed = new List<T>();
foreach (T item in collection)
if(decide(item))
removed.Add(item);
}
foreach (T item in removed)
collection.Remove(item);
removed.Clear();
class Program
class Item
public Item(string value, bool expired) { this.value = value; this.expired = expired; }
public string value;
public bool expired = false;
static void Main(string[] args)
List<Item> collection = new List<Item>();
collection.Add(new Item("one", true));
collection.Add(new Item("two", false));
collection.Add(new Item("three", true));
collection.Add(new Item("four", false));
collection.Add(new Item("five", true));
collection.Add(new Item("six", false));
collection.Add(new Item("seven", true));
collection.Add(new Item("eight", false));
collection.Add(new Item("nine", true));
I have noticed that using delegates to parametize these types of algorithms is allowing me to write much more reusable and readable code. You should take a look at the anonymous methods features and generic collections in the Beta 1 and soon the Beta 2 whidbey compilers and see how they affect your own programming style.