Why doesn't IList support AddRange

C#.NetIlist

C# Problem Overview


List.AddRange() exists, but IList.AddRange() doesn't.
This strikes me as odd. What's the reason behind this?

C# Solutions


Solution 1 - C#

Because an interface shoud be easy to implement and not contain "everything but the kitchen". If you add AddRange you should then add InsertRange and RemoveRange (for symmetry). A better question would be why there aren't extension methods for the IList<T> interface similar to the IEnumerable<T> interface. (extension methods for in-place Sort, BinarySearch, ... would be useful)

Solution 2 - C#

For those who want to have extension methods for "AddRange", "Sort", ... on IList,

Below is the AddRange extension method:

 public static void AddRange<T>(this IList<T> source, IEnumerable<T> newList)
 {
     if (source == null)
     {
        throw new ArgumentNullException(nameof(source));
     }

     if (newList == null)
     {
        throw new ArgumentNullException(nameof(newList));
     }
        
     if (source is List<T> concreteList)
     {
        concreteList.AddRange(newList);
        return;
     }

     foreach (var element in newList)
     {
        source.Add(element);
     }
}

I created a small library that does this. I find it more practical than having to redo its extension methods on each project.

Some methods are slower than List but they do the job.

Here is the GitHub to interest them:

IListExtension repository

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoris CallensView Question on Stackoverflow
Solution 1 - C#xanatosView Answer on Stackoverflow
Solution 2 - C#Emilien MathieuView Answer on Stackoverflow