I have interfaces IChild
and IParent
. IParent
has a member that is a List<IChild>
.
I wish to have classes that implement IParent
where each class has a member that implements IChild
:
public interface IChild
{
}
public interface IParent
{
List<IChild> a { get; set; }
}
public class ChildA : IChild
{
}
public class ChildB : IChild
{
}
public class ParentA : IParent
{
public List<ChildA> a { get; set; }
}
public class ParentB : IParent
{
public List<ChildB> a { get; set; }
}
But, this code will not compile. The error is:
`MyApp.Data.ParentA` does not implement interface member `MyApp.Data.IParent.a`.
`MyApp.Data.ParentA.a` cannot implement `MyApp.Data.IParent.a` because it does not have
the matching return type of `System.Collections.Generic.List<MyApp.Data.IChild>`.
Make IParent generic:
public interface IChild
{
}
public interface IParent<TChild> where TChild : IChild
{
List<TChild> a { get; set; }
}
public class ChildA : IChild { }
public class ChildB : IChild { }
public class ParentA : IParent<ChildA>
{
public List<ChildA> a { get; set; }
}
public class ParentB : IParent<ChildB>
{
public List<ChildB> a { get; set; }
}
The implementation can only return List of IChild as follows:
public interface IChild
{
}
public interface IParent
{
List<IChild> Children { get; set; }
}
public class ChildA : IChild
{
}
public class ChildB : IChild
{
}
public class ParentA : IParent
{
public List<IChild> Children
{
get;
set;
}
}
public class ParentB : IParent
{
public List<IChild> Children
{
get;
set;
}
}
You need to have the classes return a List<IChild>
:
public class ParentA : IParent
{
public List<IChild> a { get; set; }
}
public class ParentB : IParent
{
public List<IChild> a { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With