Monday, May 05, 2008

C# Extension Method for Generic Collections

{

Tinkering a bit with extension methods tonight, inspired in part by Scott Hanselman to write something I've frequently needed with generic collections: to spit them out in some delimited format.  Here are the extension class and method:

    static class EnumerableExtensions
{
public static string AsDelimited<T>(this List<T> obj, string delimiter)
{
List<string> items = new List<string>();
foreach (T data in obj) {
items.Add(data.ToString());
}
return String.Join(delimiter, items.ToArray());
}
}





You can spit out your delimited instances of any List<T> now:

            List<string> test = new List<string>(new string[] { "David", "Morgan", "Philip" });
Console.WriteLine(test.AsDelimited(" => "));

List<int> primes = new List<int>(new int[] { 2, 3, 5, 7, 11, 13, 17 });
Console.WriteLine(primes.AsDelimited(" , "));





}

1 comment:

D. Patrick Caldwell said...

Hey, I enjoyed your blog post. I've been writing a lot of extension methods lately myself. Sometimes you really have to be thankful to be a C# developer, you know?

I hadn't seen the syntax for adding an extension method to a generic type. I'm still not sure I understand why you need Foo<T>(this List<T>) and not just Foo(this List<T>).

Also, I was wondering if you've tried any syntax highlighters? I use one from google code and I have a pretty easy one liner you can add to your template. If you'd like to use it, feel free.