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?
Unfortunately, List<T>. AddRange isn't defined in any interface.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With