Variance safety in C#

Viewed 160

I believe that there is a little mistake on this part of C# documentation! But i'm not sure. Is it really a documentation mistake? or maybe am i wrong?
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/interfaces#variance-safety

instead of:

Xi is contravariant or invariant and Ai is input-safe.

it should be:

Xi is contravariant or invariant and Ai is input-UNsafe.

// test code 1
interface I1<out T>{ // T is covariant -> input-UNsafe

    I2<T> test1(); // error, I2<T> is output-unsafe! which proves my point
}
interface I2<in P> { } // P is contravariant!

I am using Visual Studio 16.7.2, Console App (.Net Framework) C# 7.3

2 Answers

This is a bug in the C# 6 draft standard (which is currently published on docs.microsoft.com). It has been fixed as part of the standardization process. You can see that in the official C# 5.0 Standard

You are right, it's most likely an error in the documentation.

In addition to the chain of reasoning in your question, which makes perfect sense, I have another (intuitive) argument in favor of this being an error:

Let's compare the last two lines of the definition of output-unsafe (A):

  • Xi is covariant or invariant and Ai is output-unsafe.
  • Xi is contravariant or invariant and Ai is input-safe.

with the last two lines of the definition of input-unsafe (B):

  • Xi is covariant or invariant and Ai is input-unsafe.
  • Xi is contravariant or invariant and Ai is output-unsafe.

Input and output safety (as well as co- and contravariance) are symmetric in C#. Thus, those two definitions should be symmetric as well, but they aren't:

              A              B         
Line 1  "output-unsafe" "input-unsafe"
Line 2  "input-safe"    "output-unsafe"
               ^
               |
               +--- strange outlier

Your proposed correction would fix that as well.

Related