Cannot implicitly convert type System.Collections.Generic.IList System.Collections.Generic.List

10,446

Call ToList on your theList object.

return theList.ToList();
Share:
10,446
user1842828
Author by

user1842828

Updated on November 23, 2022

Comments

  • user1842828
    user1842828 over 1 year

    Basically I'm converting a SQL datatable to a generic list which I can successfully do. But I can't figure out how to return the the list object. I get a error that say's a variation of- Cannot implicitly convert type System.Collections.Generic.IList to System.Collections.Generic.List

    What would be the correct way to return theList as type List?

    public List<MyObject> GetAllMyObjects()
    {
        String command = "select * from names ";
        DataTable tableResult = DataTableToList.ExecuteDataTable(command, CommandType.Text, null,connectionString);
    
        IList<MyObject> theList = DataTableToList.ConvertTo<MyObject>(tableResult);
    
        return // I’m not sure how to return theList here...
    }
    
    • tmesser
      tmesser over 11 years
      Generally you want to return interfaces so things are more loosely coupled, and therefore easier to swap out. Why do you want to return a List<T> specifically?
    • Servy
      Servy over 11 years
      @YYY Generally I prefer to return the lowest level type possible, unless I'm intentionally obscuring something. If they want to treat it as just the interface that's easy; if they need access to the lower level type (such as in this case) they then need to start doing things like casting, which causes problems.
  • user1842828
    user1842828 over 11 years
    This works thank you. The first answer I got that worked was return (List<MyObject>)theList; which also works is there any difference other than the syntax?