0
    public IList<IList<string>> GetListOfLists()
    {
        var result = new List<List<string>>();
        return result;
    }

Why does the return statement throw this compilation error when List implements IList?

Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<string>>' to 'System.Collections.Generic.IList<System.Collections.Generic.IList<string>>'. An explicit conversion exists (are you missing a cast?) c:\ConsoleApplication1\Program.cs 18 20 ConsoleApplication1

What is the best workaround?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

2 Answers2

1

Your cast would work implicitly for List<T> to IList<T>. However, List<List<T>> is not covariant with IList<IList<T>>, because the type parameter is different.

The best you can do without changing the return type is

var result = new List<IList<string>>();

It makes no difference in your situation, because IList<string> vs. List<string> changes the type, but not the content, of the returned list. In particular, you are certainly allowed to add IList<string> as elements of your result.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-2

Why not use this...

public List<List<string>> GetListOfLists()
{
    var result = new List<List<string>>();
    return result;
}

Or am I missing something you need?

user3777549
  • 419
  • 5
  • 8
  • 1
    You are missing answer to the question in your post. – Alexei Levenkov Mar 12 '16 at 02:58
  • The code IS the answer. dasblinkenlight is mixing types. My code shows to use common type of List, not IList. Make sense to you Alexei? – user3777549 Mar 12 '16 at 03:03
  • 1
    @user3777549 And that isn't answering the question. If someone asks what an apple is, and you explain what an orange is, you're not answering the question, regardless of how correct your facts about oranges are. – Servy Mar 12 '16 at 04:26