Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I posted a c# feature request here; however, I do not get a lot of attention the

ID: 643230 • Letter: I

Question

I posted a c# feature request here; however, I do not get a lot of attention there. Therefore I am asking you here, what you think of it.

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 declarations of variables, fields, parameters and possibly properties 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 because of "out" keyword!
    list.Add(new MyType()); // DISALLOWED because of "out" keyword!
}

// A List of a less derived type can be passed
public void WriteList(List<in MyType> list)
{
    MyType item = list[0]; // DISALLOWED because of "in" keyword!
    list[0] = new MyType(); // OK
    list.Add(new MyType()); // OK
}
--

UPDATE

Taken these declarations

class LessDerived { }

class MyType : LessDerived { }

class MoreDerived : MyType { }
You could use the methods shown above like this

var listOfLessDerived = new List<LessDerived>();
var listOfMyType = new List<MyType >();
var listOfMoreDerived = new List<MoreDerived>();

ReadList(listOfMyType);
ReadList(listOfMoreDerived);

WriteList(listOfMyType);
WriteList(listOfLessDerived);

Explanation / Answer

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 declarations of variables, fields, parameters and possibly properties in order to restrict the set of possible operations on any generic type in a dynamic and temporary way.

Java has this feature. An interesting fact: the "call site" variance feature in Java and the "declaration site" variance feature in C# were both designed in large part by my colleague Mads Torgersen.

I am asking you here, what you think of it.

It's a reasonable feature with many interesting scenarios. We considered it and rejected it. The benefits did not outweigh the costs.