1

I have these types in c#

public class A : IA
{

}

public interface IA
{

}

public class B
{
    public B()
    {
        A = new List<A>(); //Where I have problem
    }

    public ICollection<IA> A { get; set; }
}

I've got this cast error:

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.ICollection'. An explicit conversion exists (are you missing a cast?)

How can I do such things!

Saeed Hamed
  • 732
  • 2
  • 10
  • 28
  • 1
    Look at @Daniel answer to [this](http://stackoverflow.com/questions/2640738/c-sharp-cannot-implicitly-convert-type-listproduct-to-listiproduct) question. – Farhad Jabiyev Jul 28 '14 at 07:31
  • 1
    [C# variance problem: Assigning List as List](http://stackoverflow.com/q/2033912/284240) – Tim Schmelter Jul 28 '14 at 07:32
  • 1
    And also here is a suggested workaround: http://stackoverflow.com/questions/5832094/covariance-and-ilist/5832173#5832173 – dbc Jul 28 '14 at 07:32

1 Answers1

1

You can't implicitly convert a List to List. If you want to do that, you need to decide whether the collection should contains A or IA. Here is a fix:

public class B
{
    public B()
    {
        A = new List<IA>();
    }

    public ICollection<IA> A { get; set; }
}
Moti Azu
  • 5,392
  • 1
  • 23
  • 32