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.
Examples
// A List of a more derived type can be passed
public void ReadList(IList<out MyType> list)
{
MyType item = list[0]; // OK
list[0] = 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[0]; // DISALLOWED!
list[0] = new MyType(); // OK
list.Add(new MyType()); // OK
}
1 comment
-
Olivier J.
commented
With "variable declarations" I actually meant local variable and field declarations.