ListExtensions
Posted January 20th, 2010 by Matt Berther
I prefer to use the abstract IList
Today, I realized that I can use extension methods to add methods to interfaces.
public static class ListExtensions { public static void ForEach<T>(this IList<T> source, Action<T> action) { foreach (T item in source) action(item); } }
This now allows me to do things like:
public static void Main(string[] args) { IList<string> items = GetItems(); items.ForEach(Console.WriteLine); } private static IList<string> GetItems() { return new List<string> { "abc", "123" }; }
I much prefer this syntax to the foreach construct.
1 Comment
Bryan
January 20th, 2010
Hellz yeah. Extension methods are candy. Makes me think I may be jumping the .NET ship prematurely. Oh well, one must grow.


