Return IList <IList <T>>
I have a method that builds lists of lists. I would like the return type to use the generic IList <> interface to reduce communication with a specific List <> downstream type. However, the compiler struggles with type conversion.
public IList<IList<T>> Foo<T>()
{
return new List<List<T>>();
}
Why it doesn't work when it works:
public IList<T> Foo<T>()
{
return new List<T>();
}
What is the most elegant way out of this mess?
+5
2 answers
Just do the following:
return new List<IList<T>>();
Since it List<T>implements IList<T>, you can add any type to the result IList<T>. For instance:
Foo<int>().Add(new List<int>());
, , / ( ). , , IList<IList<T>>, - IList<T> :
Foo<int>().Add(new []{1}); // arrays implement `IList`
, List<List<T>>, : T[] List<T>. , List<T> IList<T>, a List<List<T>> IList<IList<T>>.
. .NET 4 , .
, , , , - , , IEnumerable<IList<T>>, a List<List<T>>. ? IEnumerable<T> :
public interface IEnumerable<out T>
"out" , , , T (, GetEnumerator), , -, T, (, Add).
+12