Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implement interface member because it does not have the matching return type of List<IInterface>

Tags:

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>`.
like image 304
Sergej Popov Avatar asked Aug 14 '12 15:08

Sergej Popov


3 Answers

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; }
}
like image 191
Volma Avatar answered Oct 02 '22 14:10

Volma


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;
    }
}
like image 44
nabeelfarid Avatar answered Oct 02 '22 14:10

nabeelfarid


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; }
}
like image 20
Garrett Vlieger Avatar answered Oct 02 '22 14:10

Garrett Vlieger