Search code examples
c#interfaceicollection

Adding a Collection of Interfaces to an Interface


I'm trying to wrap my head around interfaces. I keep stumbling on implimenting something like this:

public interface IFoo
{
    ICollection<IBar> Bars { get; set; }
    //some other properties
}
public interface IBar
{
    //some properties
}
//assume Bar is implemented and extends IBar. Some instaces of Bar are created
Bar[] MyBars = {bar1, bar2};
Foo MyFoo = new Foo();
MyFoo.Bars=MyBars.ToList(); //This causes an error saying Collection<Bar> cannot be
//assigned to ICollection<IBar>.

I'm completely at a loss on how to do this properly. What is the proper way to populate a collection of interfaces?

edit: The way I've implemented Foo is probably part of the problem.

public class Foo : IFoo
{
    public ICollection<IBar> Bars { get; set; }
}

Solution

  • The problem is the Foo class which should be:

    public class Foo : IFoo
    {
        public ICollection<Bar> Bars { get; set; }
    }
    

    Or if you want to use ICollection<IBar>:

    IBar[] MyBars = { bar1, bar2 };
    Foo MyFoo = new Foo( );
    MyFoo.Bars = MyBars.ToList( );
    

    Or the more elegant solution:

    Bar[] MyBars = { bar1, bar2 };
    Foo MyFoo = new Foo( );
    MyFoo.Bars = MyBars.ToList<IBar>( ); //Cast from Bar to IBar
    

    Infact the problem happened because you could't convert ICollection<Bar> to ICollection<IBar>.