0

This snippet:

static Tuple<IEnumerable<string>, IEnumerable<string>> GetTwoLists()
{
    var list1 = new List<string> { "one", "two" };
    var list2 = new List<string> { "uno", "dos" };

    return Tuple.Create(list1, list2);
}

fails to compile with error:

Cannot implicitly convert type 'System.Tuple<System.Collections.Generic.List<string>, System.Collections.Generic.List<string>>' to 'System.Tuple<System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>>'

It succeeds with an explicit cast. That is:

return Tuple.Create(list1 as IEnumerable<string>, list2 as IEnumerable<string>);

Why is the cast required here? Isn't List<string> an IEnumerable<string>?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
shnara
  • 96
  • 1
  • 5
  • 1
    `return Tuple.Create, IEnumerable>(list1, list2);` – rfmodulator Feb 25 '22 at 04:28
  • 1
    This is because Tuple types are not covariant. As an aside, consider using first class C# value tuple syntax for readability. – Aluan Haddad Feb 25 '22 at 04:32
  • 1
    Or `list1.AsEnumerable()` ... – Jeremy Lakeman Feb 25 '22 at 04:48
  • Please note that "explicit cast" in your case would be `(Tuple, IEnumerable>)Tuple.Create(list1, list2)` which fails for the same reason there is no implicit cast, the code you wrote as "explicit cast" simply creates different type of uple and removes need of the cast altogeter. (see [duplicate](https://stackoverflow.com/questions/41179199/cast-genericderived-to-genericbase) I selected) and comments above for explanation. – Alexei Levenkov Feb 25 '22 at 05:06

0 Answers0