2

The following code doesn't compile:

public void CreateStringList(out List<string> newList)
{
    newList = new List<string>();
}

...

IEnumerable<string> myList;
CreateStringList(out myList);

The error given is:

The out parameter type doesn't match the parameter type

My question is... why doesn't this work? IEnumerable<string> is covariant with List<string>, so the assignment will never violate type-safety. And you're not allowed to use an out parameter before assigning it, so the fact that the previous value of newList might not have been a List<string> is irrelevant.

Am I missing something?

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283

1 Answers1

0

Quoting Eric Lippert's answer to a very similar question (Why can't ref and out parameters be variant?):

The only difference between "out" and "ref" is that the compiler forbids reading from an out parameter before it is assigned by the callee, and that the compiler requires assignment before the callee returns normally.

This implies that languages other than C# don't have this restriction, and could use the parameter as an input. Since an IEnumerable<string> cannot be a List<string>, this is not allowed.

Community
  • 1
  • 1
Håvard S
  • 23,244
  • 8
  • 61
  • 72
  • 1
    Just a small reminder: When downvoting, please make a comment so the answer can be improved/corrected. – Håvard S Oct 18 '14 at 19:45
  • Perhaps because Eric's answer explicitly says that, and no implication is necessary: "Someone who wrote an implementation of this interface in a .NET language other than C# would be able to read from the item before it was initialized, and therefore it could be used as an input." – NetMage Feb 03 '21 at 21:27