Covariance with C# Generics -
given interface iquestion
, implementation of interface amquestion
, suppose next example:
list<amquestion> typed = new list<amquestion>(); ilist<iquestion> nontyped = typed;
this illustration yields, expected, compile error saying 2 not of same type. states explicit conversion exists. alter this:
list<amquestion> typed = new list<amquestion>(); ilist<iquestion> nontyped = typed ilist<iquestion>;
which compiles but, @ run time, nontyped
null. if explain 2 things:
it appreciated. give thanks you!
the fact amquestion
implements iquestion
interface not translate list<amquestion>
deriving list<iquestion>
.
because cast illegal, as
operator returns null
.
you must cast each item individually such:
ilist<iquestion> nontyped = typed.cast<iquestion>().tolist();
regarding comment, consider next code, usual cliché animal examples:
//lizard , donkey inherit animal list<lizard> lizards = new list<lizard> { new lizard() }; list<donkey> donkeys = new list<donkey> { new donkey() }; list<animal> animals = lizards list<animal>; //let's pretend doesn't homecoming null animals.add(new donkey()); //reality unravels!
if allowed cast list<lizard>
list<animal>
, theoretically add together new donkey
list, break inheritance.
c# generics covariance
No comments:
Post a Comment