Search code examples
c#classinterfacepropertiesilist

Class that implements an interface with IList of another interface property...how to?


I have two interfaces like these:

public interface IMyInterface1
{
    string prop1 { get; set; }
    string prop2 { get; set; }
}

public interface IMyInterface2
{
    string prop1 { get; set; }
    IList<IMyInterface1> prop2 { get; set; }
}

I have defined two classes that implement the interfaces:

public class MyClass1 : IMyInterface1
{
     public string prop1 {get; set;}
     public string prop2 {get; set;}
}

public class MyClass2 : IMyInterface2
{
     public string prop1 {get; set;}
     public IList<MyClass1> prop2 {get; set;}
}

but when I build the code I have the following error message:

'ClassLibrary1.MyClass2' does not implement interface member 'ClassLibrary1.IMyInterface2.prop2'. 'ClassLibrary1.MyClass2.prop2' cannot implement 'ClassLibrary1.IMyInterface2.prop2' because it does not have the matching return type of 'System.Collections.Generic.IList'

How can I do to implement the "IList prop2" of IMyInterface2 on my class?


Solution

  • Your interface requires that the implementing class provide a property that is of type IList<IMyInterface1>, not IList<class that implements IMyInterface1>.

    You'll need to make IMyInterface2 generic if you want this to work:

    public interface IMyInterface2<T> where T : IMyInterface1
    {
        string prop1 { get; set; }
        IList<T> prop2 { get; set; }
    }
    

    Then MyClass2 becomes:

    public class MyClass2 : IMyInterface2<MyClass1>
    {
         public string prop1 {get; set;}
         public IList<MyClass1> prop2 {get; set;}
    }