c# - Polymorphism - What am I not getting? -
i having issue polymorphism in c#. have object implements interface, cannot represent collection of objects collection of interfaces. flies in face of understanding of polymorphism. wondering have gone wrong.
[testfixture] class tester { [test] public void polymorphism() { var list = new list<foo> {new foo {name = "item"}}; assert.that(list, is.instanceof<ilist>()); assert.that(list[0], is.instanceof<foo>()); assert.that(list[0], is.instanceof<ibar>()); // why rest true false? assert.that(list, is.instanceof<ilist<ibar>>()); } } internal interface ibar { } internal class foo : ibar { public string name { get; set; } }
this question of variance, not polymorphism.
if list-of-foo ilist-of-ibar, following work:
class : ibar {} ilist<ibar> list = new list<foo>(); list.add(new another());
then we've added list of foo. error. compiler stopped making mistake.
note recent compilers / .net versions support variance via "in"/"out". list-of-foo fine ienumerable-of-ibar. because guaranteed return foo (not accept them), , foo ibar - hence safe.
Comments
Post a Comment