I created some methods that use nested type parameters generic types in the parameter declaration:
public void Foo(IList<Pair<double, IList<double>>> myParameter)
{ // code goes here
}
What I wanted to achieve was to force this method to accept 4 types of variables:
List<Pair<double, List<double>>> myVarList<Pair<double, double[]>> myVarPair<double, List<double>>[] myVarPair<double, double[]>[] myVar
But it seems that second, nested interface cannot be converted on-the-fly by C#. While trying to pass some of variables listed above to my method, I get error:
Argument 1: Cannot convert from System.Collections.Generic.List<…> to Cannot convert from System.Collections.Generic.IList<…>
Do I really need to create two aliases for this method to handle this problem? Or maybe there is some kind of trick that I could use to overcome this problem?
Your code leads to a variance problem.
The inner
IList<double>would allow you to assignList<double>even if you originally passed adouble[], which would break type safety.(This occurs fore the same reason as
List<Orange>may not be treated as aList<Fruit>: You could push apples into it.)In order to achieve correct variance behaviour, you’ll have to ensure immutability as through the use of
IEnumerable<T>s instead ofIList<T>s (just works under .NET 4.0).The previous versions of C# aren’t able to handle variance at all!