Question

In my interfaces there is typically an IList<ISomeType> to represent List-type members and to say that I expect an implementation supporting an Add method.

But in the interface implementation, there is an

IList<ISomeType> = new List<ISomeType>()

and everytime I use the List, I have to cast, for example

(this.MyList as List<IMyType>).AddRange(someType.ToList());

Is there a better way to do this? How to avoid this cast?

- edit to ask for more information -

Instead of a extension method, is there a small linq expression to solve that?

IList<string> list = new List<string>();
var items = new[] { "1", "2", "3" };
items.ToList().ForEach(x => list.Add(x));

But this does not look like being very straight forward, as it inverts what is being done. (the action is on the items to add, not on the list).

Anything better than that? Possible something that can be done on the list?

Was it helpful?

Solution

AddRange is not a method on IList, however Add is, so you can easily make an extension method:

public static void AddRange<T>(this IList<T> list, IEnumerable<T> values) {
    foreach(var value in values)
        list.Add(value);
}

You could also in your extension method check if list is actually an instance of List in which case you can call AddRange directly

OTHER TIPS

You could make an extension method suggested by Martin, but this may break stuff.

Why people use interface? To express a public contract. Now this contract is in the .NET BCL framework. If you ever expose the code to external party, you must also expose the extension method and make sure people add a using statement to the file where the extension is. Which may result in a compile time error (Something like "No AddRange method available in the IList<T>").

Additionally the extension method brakes Liskov substitution principle (substitute super type with a base type).

So if you only use List<T> in the methods, you can easily change IList<T> to List<T>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top