简体   繁体   中英

Why doesn't covariance work with out parameters?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM