tags:

views:

1059

answers:

1

I'm in a situation where I just want to append values in string array (type String[]) to an object with IList<String>. A quick look-up on MSDN revealed that IList<T>'s Insert method only has a version which takes an index and an object T, and does not have a version which takes IEnumerable<T> instead of T. Does this mean that I have to write a loop over an input list to put values into the destination list? If that's the case, it seems very limiting and rather very unfriendly API design for me. Maybe, I'm missing something. What does C# experts do in this case?

+9  A: 

Because an interface is generally the least functionality required to make it usable, to reduce the burden on the implementors. With C# 3.0 you can add this as an extension method:

public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
    if(list == null) throw new ArgumentNullException("list");
    if(items == null) throw new ArgumentNullException("items");
    foreach(T item in items) list.Add(item);
}

et voila; IList<T> now has AddRange:

IList<string> list = ...
string[] arr = {"abc","def","ghi","jkl","mno"};
list.AddRange(arr);
Marc Gravell
you could do that, but its has its risks, when you call AddRange, you may expect the underlying object to have some understanding that it is operating on a range. In a databinding scenario this may end up triggering thousands of events in a scenario where one event would have been enough.
Sam Saffron
@Sam; indeed; but it is the best that you can do via IList<T>; there are ways to compensate, of course...
Marc Gravell
Thanks for the answer Marc. I still kind of feel that the interface should be designed in a way that the usability is weighted more than the ease of implementability, considering that appending a list to another list is such a common operation. Anyway, extension method serves really nicely in this case, so it might not be anything to fuss about..
Kei
@Kei - but it is largely redundant (i.e. the same can already be achieved), so I can understand it not existing as an extra interface method.
Marc Gravell
What's with the 'horrible' curly brace placement? ;)
Mitch Wheat