The question maybe a little confusing, but it’s hard to make clear this question in a subject title.
I have method declared and implemented like this:
public IList<string> GetBookTitles()
{
IList<string> bookTitles = new List<string>();
// do something to populate the bookTitles list.
return bookTitles;
}
Why can’t I pass the result of this method to a List<string>? After all, List<string> is a kind of IList<string>.
Well, for starters, just look at the members of
IListand compare it withList.Listhas methods that anIListdoesn’t. (Listhas aBinarySearchmethod thatIListdoesn’t, just as a single example.)Arrays also implement
IList, as an example. An array however is not aList, so you can’t, and shouldn’t, be able to pass astring[]to a method that accepts aList<string>.You have a few possible solutions. One would be to just change your method to return a
List<string>rather than anIList<string>(that’s what I’d suggest). If that’s what you really need then you shouldn’t be restricting the return type toIList<string>. Another (poorer) option would be to cast the result back to aList<string>before passing it to the next method, since you happen to know that it’s what the underlying type really is.