Reputation: 5534
I have a component that accept two types as datasource
public interface Ia
{
....
ICollection<Ib> Detail{ get; set; }
}
public interface Ib
{
....
}
Then I have two EF classes that implements the interfaces
public class b:Ib
{
}
And here is my problem. How to cast MyDetail to Detail and Detail to MyDetail, I'm trying to use Detail to encapsulate MyDetail
public class a : Ia
{
public virtual ICollection<b> MyDetail{get;set;}
// How to cast MyDetal to Detail and Detail to MyDetail
// Something like
public virtual ICollection<Ib> Detail
{
get {return MyDetail;}
set {MyDetail = value;}
}
}
Is this posible? there is another aproach to perform this conversión ?
Upvotes: 0
Views: 117
Reputation: 203822
You cannot do this. ICollection
is not covariant, so you cannot treat a ICollection<b>
as a ICollection<Ib>
(in the getter), and its not contravariant, so you can't treat a ICollection<Ib>
as a ICollection<b>
(in the setter). ICollection<T>
is invariant. (Note that it's impossible for anything to ever be both contravariant and covariant.
For your getter the best that you could do is create a new collection and copy over all of the elements. You know it will succeed, but you do need to make the copy.
For your setter you would also need to make a new collection, but here you have no idea of all of the items actually are b
objects, so you need to know how to handle any that aren't (do you omit them, throw an exception, or what).
Upvotes: 1