Why ExMethodError
Fails?
public IList<IList<T>> ExMethodError() {
return new List<List<T>>(); // ERROR
}
You're trying to return List<List<T>>
where the return type is IList<IList<T>>
.
This looks superficially okay, because List<T>
is direved from IList<T>
.
But here's the key:
Generic interfaces like
IList<T>
are invariant.
That means:
List<T>
implementsIList<T>
, butList<List<T>>
does not implementIList<IList<T>>
.
Because variance doesn't apply here.
It will work in this way
// Only works with interfaces that are covariant, like IEnumerable<T>
public IEnumerable<IEnumerable<T>> ExMethodWithCovariance() {
return new List<List<T>>(); // This works!
}
For further assitance please check this link