Main menu:

Site search

Categories

March 2010
M T W T F S S
« Jan    
1234567
891011121314
15161718192021
22232425262728
293031  

Tags

Blogroll

Making C# IList Useable

Around my neck of the woods, I have been having a theoretical debate with my colleague Dan Bodart as to the best method signature when it comes to collections of data.

Dan’s point of view is that in order to be good citizens, our methods should form around interfaces and not rely on the concrete representation, after all if you need the data as a list, you can always create a new one.

My argument is that the IList interface is so rubbish that you would always need to create a list in order to manipulate it, and then that just becomes noise.

Both sides of the argument have valid points, and valid critisisms. After a little searching, we have found the answer: use extension methods for IList to add the fantastic list methods to the interface. In fact, we have gone one step further, and added extention methods to IEnumerable, so that we can have the power for our dictionaries as well. We have taken the opportunity to add a lot more functional methods  such as Head, Tail, Exists,  Find and AsString.

Here is an exerpt from our class.


    public static class EnumerableExtensionMethods

    {

        public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)

        {

            foreach (T t in source)

            {

                action(t);

            }

        }

 

        public static List<T> ConvertAll<S, T>(this IEnumerable<S> source, Converter<S, T> converter)

        {

            return new List<S>(source).ConvertAll(converter);

        }

 

        public static List<T> FindAll<T>(this IEnumerable<T> source, Predicate<T> predicate)

        {

            return new List<T>(source).FindAll(predicate);

        }

    }
<div>

Comments

Comment from Dale
Time May 11, 2009 at 5:18 pm

Any reason why you decided to return List?

Comment from Dale
Time May 11, 2009 at 5:20 pm

By ‘List?’ I mean a generic list. I think my pointy brackets were removed by your blogging engine

Comment from Sarah
Time May 11, 2009 at 6:43 pm

The latest wordpress upgrade didn’t go so well for the code blocks – apologies for this

Comment from Sarah
Time May 11, 2009 at 6:45 pm

@Dale – Nope – I believe these could be IEnumerable too.

Write a comment