Add support for covariance for methods with array-like output #2055
Replies: 4 comments
-
The variance of arrays in the CLR is considered one of the bigger mistakes of .NET, an unfortunate relic copied from Java. |
Beta Was this translation helpful? Give feedback.
-
Variance of array is not a variance of ReadOnlySpan. Because you are unable to do the bad things. var strs = new string[10];
var objs = (object[])strs; // Here the hell openning.
objs[0] = new object(); // DAMAGE !!! This is DOTNET mistake inherited from JAVA!
Console.WriteLine(strs[0]); // BOOM! Here CLR should do a lots of different additional checks to detect the DAMAGE
// Output :
// Unhandled Exception: System.ArrayTypeMismatchException:
// Attempted to access an element as a type incompatible with the array. With downcasting of ReadOnlySpan you have no such problem. var a = new string[] {"Hello!"};
ReadOnlySpan<string> strs = a;
ReadOnlySpan<object> objs = a; // Should be cast but it's currently impossible in C#
Console.WriteLine(objs[0]); // this is totally safe, no any extra check is required in CLR For example "System.Runtime.CompilerServices.Unsafe.As" allows to do any wierd thing, but nobody says that is "WORST ERROR" in dotnet history. |
Beta Was this translation helpful? Give feedback.
-
This could be summarized by "interface-like structs with variant". Some others will benifit from it as well, like ValueTask. |
Beta Was this translation helpful? Give feedback.
-
Related to #317 (comment), covariant structs |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Motivation
Spans becomes popular in method signatures.
It's very usefull for performance general purpose libraries to allow covariant "array-like" output from a method.
For example modern enumerables (#2053) can be built with the covariant array-like output.
Proposal
Beta Was this translation helpful? Give feedback.
All reactions