c# - Error Applying Entity relation design with Abstract Classes when assigning a List containing a more derived class -
i'm defining 2 abstract classes: ac1
, , ac2
. ac1
has property (variable) list
of type ac2
(list<ac2>
) (that's way of defining 1 many relation).
then, defined r1
comes ac1
(r1 : ac1
) , r2 : ac2
. problem comes when i'm writing r1's constructor. i'm passing parameter list of type r2 (list<r2>
) , try assign property (variable) defined in ac1 (list<ac2>
), fails cannot implicitly convert r2 ac2 (even when r2 comes ac2).
code example:
abstract class ac2 { //several properties , methods here } abstract class ac1 { list<ac2> dammvariable {get; set;} //problematic variable (see class r1) //other stuff here } class r2 : ac2 { //some properties exclusive r2 here public r2(){} } class r1 : ac1 { //some properties exclusive r1 here public r1(list<r2> r2s) { this.dammvariable = r2s; //i found error right here } }
i'll have other classes coming abstract classes, each time create class (x2, example) comes ac2 i'll need x1 class has list<x2>
.
am failing in design or implementation?
i'll appreciate help.
there's couple issues here.
firstly, you'll need change protection level of
dammvariable
@ leastprotected
in order access in subclasses.but you'll faced type safety problem:
cs0029: cannot implicitly convert type
system.collections.generic.list<r2>
system.collections.generic.list<ac2>
this because list<t>
invariant, not able assign list<r2>
list<ac2>
despite inheritance relationship between r2
, ac2
.
assuming once assigned, never need add / remove elements dammvariable
, change type list type allows covariance, e.g.
abstract class ac1 { protected ienumerable<ac2> dammvariable {get; set;} )
more on covariance / contravariance in this question
Comments
Post a Comment