I have written a method which is
public List<List<object>> Fetch(string data),
inside I create
List<List<object>> p = new List<List<object>>();
my boss now wants to return a IList<IList<object>> instead of List<List<object>> ie
public IList<IList<object>> Fetch(string data),
so when I try do
return (IList<IList<object>>) p; //throws an exception
How do I convert
List<List<object>> to IList<IList<object>> and back to List<List<object>>
You can’t perform that conversion via straight casting – it wouldn’t be safe. Instead, you should use:
Then for each “sublist” you can use:
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:
Then this would be valid:
But
p[0]is a reference to anobject[], not aList<object>… our supposedly type-safe code doesn’t look as safe any more…Fortunately,
IList<T>is invariant to prevent exactly this problem.