Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why IList<T> does not have Insert methods which take IEnumerable<T>?

Tags:

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?

like image 636
Kei Avatar asked Jul 12 '09 22:07

Kei


People also ask

Is it possible to use Add or AddRange methods on IEnumerable?

Unfortunately, List<T>. AddRange isn't defined in any interface.

What is difference between list and IList in C#?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.

Does string implement IList?

The fact that String does not implement IList<char> doesn't surprise me. In fact, what does surprise me somewhat, is that it implements IEnumerable<char> . Why? Because a string is not really a sequence of chars.

What is IList type in C#?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.


1 Answers

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); 
like image 137
Marc Gravell Avatar answered Oct 04 '22 02:10

Marc Gravell