See the code below:
public class CustomList : List<string>
{ }
public class BaseService
{
public BaseService(KeyValuePair<List<string>, string> p1)
{ }
}
public class DerivedService : BaseService
{
public DerivedService(KeyValuePair<CustomList, string> p1) : base(p1)
{ }
}
I have a compilation error in base(p1)
:
The compiler cannot cast KeyValuePair<CustomList, string>
to KeyValuePair<List<string>, string>
(I used types KeyValuePair
and List
to simplify the example, but in my case, they are generic types that are not part of the framework).
I managed to refactor the code differently, but I'm still curious: it seems to me that it safe to do the cast in this case. Why does the compiler refuse it?
This is also surprising because if I replace KeyValuePair
with an interface with the covariance out keyword (IMyInterface<out T1, T2>
), it compiles.
, string>` are different types
, string> p1) { p1.Key = new AnotherListThatAlsoDerivesFromListString() }`. [Don´t put giraffes and lions together](https://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase).
– MakePeaceGreatAgain Dec 13 '19 at 15:01