Querying types in a co- or contravariant way
The "in" and "out" keywords in generic type declarations are useful; however, due to their nature, their application is limited to a small number of types. What I am suggesting here, is to be able to use them in variable, parameter and possibly property declarations in order to restrict the set of possible operations on any generic type in a dynamic and temporary way. This would considerably increase the cases where co- and contravariance could be used.
// A List of a more derived type can be passed
public void ReadList(IList<out MyType> list)
MyType item = list; // OK
list = new MyType(); // DISALLOWED!
list.Add(new MyType()); // DISALLOWED!
// A List of a less derived type can be passed
public void WriteList(List<in MyType> list)
MyType item = list; // DISALLOWED!
list = new MyType(); // OK
list.Add(new MyType()); // OK
Thank you for your suggestion! While we aim to respond to every suggestion, we are closing older ones that don’t have enough votes so newer ones from you can move to the top. If this suggestion is still important to you, feel free to open it again.
Olivier J. commented
With "variable declarations" I actually meant local variable and field declarations.