convert List to IList

You can’t perform that conversion via straight casting – it wouldn’t be safe. Instead, you should use:

IList<IList<object>> ret = new List<IList<object>>();

Then for each “sublist” you can use:

// Or whatever
ret.Add(new List<object>());

Finally, just return ret.

You could use LINQ to perform the conversion of your existing List<List<object>> when you return it – but it would be better to just create a more appropriate type to start with, as shown above.


To understand why some of the existing answers are wrong, suppose you could do this:

IList<IList<object>> p = new List<List<object>>();

Then this would be valid:

List<List<object>> listOfLists = new List<List<object>>();
IList<IList<object>> p = listOfLists;
p.Add(new object[]);
List<object> list = p[0];

But p[0] is a reference to an object[], not a List<object>… our supposedly type-safe code doesn’t look as safe any more…

Fortunately, IList<T> is invariant to prevent exactly this problem.

Leave a Comment